Searching

Sorting and Searching

  • Sorting search results on a page given a certain set of criteria.

  • Sort a list of numbers in which each number is at a distance K from its actual position.

  • Given an array of integers, sort the array so that all odd indexes are greater than the even indexes.

  • Given users with locations in a list and a logged-in user with locations, find their travel buddies (people who shared more than half of your locations).

  • Search for an element in a sorted and rotated array.

  • Sort a list where each element is no more than k positions away from its sorted position.

  • Search for an item in a sorted, but rotated, array.

  • Merge two sorted lists together.

  • Give 3 distinct algorithms to find the K largest values in a list of N items.

  • Find the minimum element in a sorted rotated array in faster than O(n) time.

  • Write a function that takes a number as input and outputs the biggest number with the same set of digits.

# linear search O(n)
def name_in_phonebook(to_find, phonebook):
    for name in phonebook:
        if name == to_find:
            return True
    return False

# binary search O(log n)
def name_in_phonebook_2(to_find, name):
    # sentinal , edge case
    if len(to_find) == 0:
        return False
    # set first element to zero
    first = 0
    # set the last items to size - 1
    last = (len(to_find) - 1)
    # set a found flag to false
    found = False

    # loop until either found or end of list
    while first <= last and not found:
        # find the middle of the list using interger division //
        middle = (first + last) // 2

        # if found update found variable
        if to_find[middle] == name:
            found = True
        # otherwise
        else:
            # if name  is to the left of the data
            if name < to_find[middle]:
                # search the lower half
                last = middle - 1
            # otherwise
            else:
                # search the upper half
                first = middle + 1 
    # return found
    return found
from collections import deque
from collections.abc import Callable, Iterable, Mapping

from src.typehints import Node


def bfs_search_dict(graph: Mapping[Node, Iterable[Node]], start: Node, predicate: Callable[[Node], bool]) -> bool:
    """Find the closest node to start that matches the predicate using breadth first search."""
    visited = set()
    to_visit = deque([start])
    while to_visit:
        node = to_visit.popleft()
        if node in visited:
            continue
        visited.add(node)
        if predicate(node):
            return True
        to_visit += graph[node]
    return False
ArrayBinary Search TreeLinked ListExtra-ArrayStackBinary TreeRecursionHash TableSearchingSortingQueue SandboxHash TableDouble Linked ListGraphsExoticHeap

Last updated