LearnFrenzy
Sign in Take a free test

Data Structures interview · Set 6 of 14

Sorting and Searching

  • 5 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Know the trade-offs, master binary search

For sorting, interviewers want trade-offs (stability, memory, worst case). For searching, they want you to adapt binary search: boundaries, rotated arrays and searching on the answer.

  • SortingMerge vs quick sort, stability, counting sort.
  • Binary searchTemplate, boundaries and variants.
  • Two pointersLinear-time pair and window problems.

You will rarely be asked to code bubble sort, but you will be asked why merge sort is stable, why quick sort is fast in practice, and — very often — to adapt binary search to an unusual problem. Binary search is the single most reusable trick in coding rounds.

1. Compare merge sort and quick sort.

Merge sort splits the array, sorts both halves and merges them: always O(n log n), stable, but needs O(n) extra space. Quick sort partitions around a pivot: O(n log n) on average, O(n²) worst case, in place, and very cache-friendly, which makes it fast in practice. Java sorts primitives with a dual-pivot quick sort and objects with TimSort (a stable merge-sort hybrid).


2. What does it mean for a sort to be stable? Why does it matter?

A stable sort keeps equal elements in their original order. It matters when you sort by several keys in turn: sort orders by date, then stably by customer, and each customer's orders stay in date order.


3. Write binary search without bugs.

Keep the search space as [lo, hi], compute the middle without overflow, and move one side past the middle each time.

int search(int[] a, int target) {
    int lo = 0, hi = a.length - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;      // avoids int overflow
        if (a[mid] == target) return mid;
        if (a[mid] < target) lo = mid + 1; else hi = mid - 1;
    }
    return -1;
}

4. Find the first position of a target in a sorted array with duplicates.

When you find the target, record it and keep searching left. The same idea with “keep searching right” gives the last position; together they count occurrences in O(log n).

int firstIndex(int[] a, int t) {
    int lo = 0, hi = a.length - 1, ans = -1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] >= t) { if (a[mid] == t) ans = mid; hi = mid - 1; }
        else lo = mid + 1;
    }
    return ans;
}

5. Search in a rotated sorted array.

At least one half around mid is always sorted. Check whether the target lies inside that sorted half; if yes, search there, otherwise search the other half. Still O(log n).

int searchRotated(int[] a, int t) {
    int lo = 0, hi = a.length - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == t) return mid;
        if (a[lo] <= a[mid]) {                       // left half sorted
            if (a[lo] <= t && t < a[mid]) hi = mid - 1; else lo = mid + 1;
        } else {                                     // right half sorted
            if (a[mid] < t && t <= a[hi]) lo = mid + 1; else hi = mid - 1;
        }
    }
    return -1;
}

6. What is “binary search on the answer”?

When the answer is a number and you can check “is x good enough?” in a way that is monotonic (if x works, every bigger x works too), binary search over possible answers. Examples: minimum ship capacity to deliver packages in D days, minimum eating speed, maximum minimum distance.


7. Explain the two-pointer technique with an example.

Two indices move towards each other or in the same direction to avoid a nested loop. In a sorted array, finding a pair with a given sum: move the left pointer up if the sum is too small, the right pointer down if too big — O(n) instead of O(n²).

boolean hasPair(int[] sorted, int target) {
    int i = 0, j = sorted.length - 1;
    while (i < j) {
        int s = sorted[i] + sorted[j];
        if (s == target) return true;
        if (s < target) i++; else j--;
    }
    return false;
}

8. When would you use counting sort or radix sort?

When keys are integers in a small range (exam marks 0–100, ages), counting sort runs in O(n + k) — faster than any comparison sort, whose lower bound is O(n log n). Radix sort extends the idea digit by digit for larger fixed-width keys.


Remember

Key points

  • Comparison sorts are Ω(n log n)

    Counting sort beats it only for small key ranges.

  • lo + (hi - lo) / 2

    Avoids integer overflow in binary search.

  • Monotonic check → binary search

    Search the answer space, not just arrays.

  • Sorted input → two pointers

    Turns O(n²) pair searches into O(n).

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 How do you avoid quick sort's worst case? Intermediate

    Pick a random pivot or the median of three, and use three-way partitioning when there are many duplicates.

  2. 2 Find the square root of a number without Math.sqrt. Intermediate

    Binary search on the answer between 0 and x, checking mid * mid <= x (use long to avoid overflow).

  3. 3 How would you sort a 10 GB file with 1 GB of RAM? Advanced

    External merge sort: sort chunks that fit in memory, write them to disk, then k-way merge them with a min-heap.

    Key insight: When data does not fit in memory, think chunks + merge.

  4. 4 Find the k-th largest element faster than sorting. Advanced

    Quickselect gives O(n) on average; a min-heap of size k gives O(n log k).

  5. 5 Which sorting algorithm is best for an almost-sorted array? Basic

    Insertion sort runs in nearly O(n) on almost-sorted data, which is why TimSort uses it for small runs.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links