Array Searching Problems

Solve one Java logic problem at a time, then flip for the complete explanation and program.

0/156 Known filtered set
Difficulty
Read Full Guide Question: 1 of 156

Java Logic Development · Chapter 10 Companion Article

Array Searching Problems

Fourteen searching problems — linear and binary search, occurrence boundaries, rotated arrays, missing and duplicate values, and set-based comparisons — each chosen by asking what the data allows.

Overview

Array searching problems test how well you can locate, count, compare, and identify values inside arrays. Some problems require simple traversal, while others depend on sorted data, binary search, hashing, XOR, or index-based logic.

The correct technique depends mainly on:

  • Whether the array is sorted.
  • Whether duplicate values are allowed.
  • Whether only one result or all matching results are required.
  • Whether extra memory can be used.
  • Whether the problem provides special constraints such as values from 1 to n.

Searching Techniques Used in This Chapter

Problem TypeMain TechniqueTypical Time
Unsorted searchLinear SearchO(n)
Sorted searchBinary SearchO(log n)
First/Last occurrenceModified Binary SearchO(log n)
Count in sorted arrayFirst + Last occurrenceO(log n)
Rotated sorted arrayModified Binary SearchO(log n)
Missing valueArithmetic / XORO(n)
Single duplicateFloyd's Cycle DetectionO(n)
Multiple duplicatesHashSet / Frequency MapO(n)
Unique valueXORO(n)
Common valuesHashSetO(n + m)
Uncommon valuesSet DifferenceO(n + m)

1. Linear Search

Linear search checks array elements one after another until the required element is found. It works with sorted arrays, unsorted arrays, primitive arrays, and small datasets where simplicity is more useful than optimization.

Find the index of a target element in an unsorted integer array.

Input
Array: [24, 7, 18, 42, 11]
Target: 42
Output
Element found at index: 3

Traverse the array from left to right. For every index i: compare array[i] with target. If they are equal, return i. If traversal finishes without a match, return -1. Returning immediately avoids unnecessary comparisons after the element is found.

Java
public class LinearSearch {
    public static void main(String[] args) {
        int[] numbers = {24, 7, 18, 42, 11};
        int target = 42;
        int index = -1;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == target) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            System.out.println("Element found at index: " + index);
        } else {
            System.out.println("Element not found");
        }
    }
}
Output
Element found at index: 3
inumbers[i]TargetMatch
02442No
1742No
21842No
34242Yes

The loop stops at index 3.

  • Best case: O(1)
  • Worst case: O(n)
  • Space: O(1)
  • Empty array.
  • Target at index 0.
  • Target at the last index.
  • Target not present.
  • Duplicate targets when only the first match is needed.

Do not assume linear search returns all occurrences. This version intentionally stops at the first match.

Use linear search when the input is unsorted and preprocessing or sorting is not justified.

2. Binary Search

Binary search repeatedly divides the searchable portion of a sorted array into two halves. It requires the array to be sorted.

Search for a target value in a sorted array.

Input
Array: [4, 9, 15, 21, 28, 36, 44]
Target: 28
Output
Element found at index: 4

Maintain two indexes: low (beginning of the current search range) and high (end of the current search range). Calculate mid = low + (high - low) / 2. Then: if array[mid] equals target, return mid. If target is smaller, move high left. If target is larger, move low right.

Java
public class BinarySearch {
    public static void main(String[] args) {
        int[] numbers = {4, 9, 15, 21, 28, 36, 44};
        int target = 28;
        int low = 0;
        int high = numbers.length - 1;
        int index = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (numbers[mid] == target) {
                index = mid;
                break;
            } else if (numbers[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        if (index != -1) {
            System.out.println("Element found at index: " + index);
        } else {
            System.out.println("Element not found");
        }
    }
}
Output
Element found at index: 4

Initial:

Text
low = 0
high = 6

First middle:

Text
mid = 3
numbers[3] = 21

28 is greater than 21: low = 4. Next:

Text
mid = 5
numbers[5] = 36

28 is smaller: high = 4. Next:

Text
mid = 4
numbers[4] = 28

Target found.

  • Best case: O(1)
  • Worst case: O(log n)
  • Space: O(1) for iterative implementation.

Applying binary search directly to an unsorted array produces unreliable results.

Prefer the overflow-safe middle calculation: int mid = low + (high - low) / 2;

3. First Occurrence of Element

Problem

A sorted array may contain duplicate values. Find the index where the target appears for the first time.

Example

Input
Array: [2, 5, 5, 5, 8, 12]
Target: 5
Output
First occurrence: 1

Logic

Use binary search with one important modification. When target is found: store mid in result, then continue searching from low to mid - 1. This checks whether another occurrence exists at a smaller index.

Java Program

Java
public class FirstOccurrence {
    public static void main(String[] args) {
        int[] numbers = {2, 5, 5, 5, 8, 12};
        int target = 5;
        int low = 0;
        int high = numbers.length - 1;
        int result = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (numbers[mid] == target) {
                result = mid;
                high = mid - 1;
            } else if (numbers[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        System.out.println("First occurrence: " + result);
    }
}

Program Output

Output
First occurrence: 1

Dry Run

First match may occur at index 2. Instead of stopping:

Text
result = 2
high = 1

Search continues on the left. Index 1 also contains 5: result = 1. No earlier 5 exists.

Complexity

  • Time: O(log n)
  • Space: O(1)

Common Mistake

Using ordinary binary search and assuming the returned matching index is the first occurrence.

Interview Tip

Questions involving duplicate values often require modified binary search rather than standard binary search.

4. Last Occurrence of Element

Problem

Find the final index where a target appears in a sorted array.

Example

Input
Array: [2, 5, 5, 5, 8, 12]
Target: 5
Output
Last occurrence: 3

Logic

When array[mid] equals target: save mid, then set low = mid + 1. The search continues to determine whether the same value appears later.

Java Program

Java
public class LastOccurrence {
    public static void main(String[] args) {
        int[] numbers = {2, 5, 5, 5, 8, 12};
        int target = 5;
        int low = 0;
        int high = numbers.length - 1;
        int result = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (numbers[mid] == target) {
                result = mid;
                low = mid + 1;
            } else if (numbers[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        System.out.println("Last occurrence: " + result);
    }
}

Program Output

Output
Last occurrence: 3

Dry Run

Target is found at index 2. Search continues right:

Text
result = 2
low = 3

Index 3 also contains 5: result = 3. No later matching value exists.

Complexity

  • Time: O(log n)
  • Space: O(1)

Common Mistake

Moving high to mid - 1 after finding the target would search for the first occurrence instead.

5. Count Occurrences of Element

Problem

Count how many times a target occurs in a sorted array.

Example

Input
Array: [1, 3, 3, 3, 3, 7, 9]
Target: 3
Output
Occurrences: 4

Logic

If first is the first index of target and last is the last index of target, then count = last - first + 1. This avoids scanning every duplicate.

Java Program

Java
public class CountOccurrences {
    private static int findBoundary(int[] numbers, int target, boolean first) {
        int low = 0;
        int high = numbers.length - 1;
        int result = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (numbers[mid] == target) {
                result = mid;
                if (first) {
                    high = mid - 1;
                } else {
                    low = mid + 1;
                }
            } else if (numbers[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return result;
    }
    public static void main(String[] args) {
        int[] numbers = {1, 3, 3, 3, 3, 7, 9};
        int target = 3;
        int first = findBoundary(numbers, target, true);
        int last = findBoundary(numbers, target, false);
        int count = first == -1 ? 0 : last - first + 1;
        System.out.println("Occurrences: " + count);
    }
}

Program Output

Output
Occurrences: 4

Dry Run

For target 3:

Text
first = 1
last = 4

Therefore:

Text
count = 4 - 1 + 1
count = 4

Complexity

Two binary searches are performed:

  • Time: O(log n)
  • Space: O(1)

Alternative Approach

A linear scan can count occurrences in O(n), which is suitable when the array is unsorted.

Interview Tip

When the interviewer explicitly says the array is sorted, look for an O(log n) solution before using a full traversal.

6. Search Element in Sorted Array

Problem

Determine whether an element exists in an ascending sorted array. Unlike the earlier binary-search example that returns an index, this variation focuses on a boolean membership check.

Example

Input
Array: [10, 20, 30, 40, 50, 60]
Target: 40
Output
Element exists: true

Hint

Discard half of the remaining array after every comparison.

Java Program

Java
public class SearchSortedArray {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50, 60};
        int target = 40;
        int low = 0;
        int high = numbers.length - 1;
        boolean found = false;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (numbers[mid] == target) {
                found = true;
                break;
            }
            if (numbers[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        System.out.println("Element exists: " + found);
    }
}

Program Output

Output
Element exists: true

Why Sorted Order Matters

Suppose the middle element is 30 and the target is 40. Because the array is ascending, everything before 30 can also be discarded. Without sorted order, that conclusion would not be valid.

Complexity

  • Time: O(log n)
  • Space: O(1)

Practical Note

Java also provides Arrays.binarySearch(), but implementing the algorithm manually is important for logic-development and interview questions.

7. Search Element in Rotated Array

What Is a Rotated Sorted Array?

A sorted array may be shifted around a pivot. Example:

Text
Original: [1, 2, 3, 4, 5, 6, 7]
Rotated:  [4, 5, 6, 7, 1, 2, 3]

The complete array is no longer sorted, but at least one half around the middle remains sorted.

Problem

Search for a target in a rotated sorted array containing distinct values.

Example

Input
Array: [40, 50, 60, 70, 10, 20, 30]
Target: 20
Output
Element found at index: 5

Logic

After calculating mid: check whether target equals array[mid]. Determine whether the left half is sorted. If target lies inside that sorted half, search there. Otherwise search the opposite half.

Java Program

Java
public class SearchRotatedArray {
    public static void main(String[] args) {
        int[] numbers = {40, 50, 60, 70, 10, 20, 30};
        int target = 20;
        int low = 0;
        int high = numbers.length - 1;
        int result = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (numbers[mid] == target) {
                result = mid;
                break;
            }
            if (numbers[low] <= numbers[mid]) {
                // Left half is sorted
                if (target >= numbers[low] && target < numbers[mid]) {
                    high = mid - 1;
                } else {
                    low = mid + 1;
                }
            } else {
                // Right half is sorted
                if (target > numbers[mid] && target <= numbers[high]) {
                    low = mid + 1;
                } else {
                    high = mid - 1;
                }
            }
        }
        System.out.println("Element found at index: " + result);
    }
}

Program Output

Output
Element found at index: 5

Dry Run

Initial middle:

Text
mid = 3
numbers[mid] = 70

Left half [40, 50, 60, 70] is sorted. 20 does not lie between 40 and 70, so search right. New range: [10, 20, 30]. The target is found at original index 5.

Complexity

  • Time: O(log n) when values are distinct.
  • Space: O(1).

Important Edge Case

Heavy duplication can make it difficult to determine which half is sorted. Some duplicate-aware versions may degrade toward O(n).

Interview Tip

Do not sort the rotated array first unless the problem allows changing the complexity. Sorting would usually make the solution O(n log n).

8. Find Missing Element

Problem

An array contains distinct numbers from 1 to n, but exactly one number is missing. Find the missing number.

Example

Input
Array: [1, 2, 3, 5, 6]
Expected range: 1 to 6
Output
Missing element: 4

Logic

The sum of numbers from 1 to n is n * (n + 1) / 2. Then missing = expectedSum - actualSum. For production code with large n, long should be used to reduce integer-overflow risk.

Java Program

Java
public class MissingElement {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 5, 6};
        int n = 6;
        long expectedSum = (long) n * (n + 1) / 2;
        long actualSum = 0;
        for (int number : numbers) {
            actualSum += number;
        }
        long missing = expectedSum - actualSum;
        System.out.println("Missing element: " + missing);
    }
}

Program Output

Output
Missing element: 4

Dry Run

Expected: 1 + 2 + 3 + 4 + 5 + 6 = 21. Actual: 1 + 2 + 3 + 5 + 6 = 17. Difference: 21 - 17 = 4.

Complexity

  • Time: O(n)
  • Space: O(1)

Alternative Approach: XOR

XOR can also find the missing value without arithmetic-sum overflow.

Important Assumption

This formula works only when values belong to the expected 1 to n range, exactly one value is missing, and other values are not duplicated.

Common Mistake

Using the arithmetic formula without verifying the input constraints.

9. Find Duplicate Element

Problem

An array contains n + 1 integers where every value is between 1 and n. Exactly one value is duplicated, although it may appear more than twice. Find that duplicate without modifying the array and using constant extra space.

Example

Input
[1, 3, 4, 2, 2]
Output
Duplicate element: 2

Logic

Treat each array value as the index of the next node in a linked structure. Under the stated constraints, repeatedly following next = numbers[current] creates a cycle. The duplicate value acts as the entry point of that cycle.

Floyd's cycle detection uses slow (moves one step) and fast (moves two steps). After they meet, reset slow to the beginning. Move both one step at a time. Their next meeting point identifies the duplicate.

Java Program

Java
public class FindDuplicate {
    public static void main(String[] args) {
        int[] numbers = {1, 3, 4, 2, 2};
        int slow = numbers[0];
        int fast = numbers[0];
        do {
            slow = numbers[slow];
            fast = numbers[numbers[fast]];
        } while (slow != fast);
        slow = numbers[0];
        while (slow != fast) {
            slow = numbers[slow];
            fast = numbers[fast];
        }
        System.out.println("Duplicate element: " + slow);
    }
}

Program Output

Output
Duplicate element: 2

Why It Works

Each valid array value points to another valid index. Because there are more positions than unique allowed values, at least one path must revisit a previously reached position. The repeated value creates the cycle entry.

Complexity

  • Time: O(n)
  • Space: O(1)

Important Assumptions

This technique depends on strict constraints: array length is n + 1, every value is between 1 and n, and a duplicate is guaranteed. It is not a general-purpose duplicate finder for arbitrary integers.

Interview Tip

This problem tests whether you can recognize a hidden linked-list/cycle structure inside an array.

10. Find Multiple Duplicate Elements

Problem

An arbitrary array may contain several different duplicate values. Find every value that occurs more than once.

Example

Input
[4, 7, 2, 4, 9, 7, 7, 3, 2]
Output
Duplicate elements: [4, 7, 2]

Logic

For each number: try to add it to seen. If seen.add() returns false, the number already exists, so add that number to duplicates. A LinkedHashSet preserves the order in which duplicate values are first detected.

Java Program

Java
import java.util.LinkedHashSet;
import java.util.Set;
public class MultipleDuplicates {
    public static void main(String[] args) {
        int[] numbers = {4, 7, 2, 4, 9, 7, 7, 3, 2};
        Set seen = new LinkedHashSet<>();
        Set duplicates = new LinkedHashSet<>();
        for (int number : numbers) {
            if (!seen.add(number)) {
                duplicates.add(number);
            }
        }
        System.out.println("Duplicate elements: " + duplicates);
    }
}

Program Output

Output
Duplicate elements: [4, 7, 2]

Dry Run

After reading first 4: seen = [4]. Second 4:

Text
4 already exists
duplicates = [4]

Second 7: duplicates = [4, 7]. Second 2: duplicates = [4, 7, 2]. The third occurrence of 7 does not create another output entry because duplicates is also a set.

Complexity

Average case:

  • Time: O(n)
  • Space: O(n)

Why Two Sets?

Using only seen tells whether a value was encountered previously, but repeatedly printing on every repeated occurrence could produce duplicate output lines for a value appearing three times. The duplicates set keeps each duplicated value only once.

11. Find Unique Element

Problem

Every element appears exactly twice except one element that appears once. Find the unique value.

Example

Input
[6, 4, 9, 4, 6]
Output
Unique element: 9

XOR Properties

For any integer x:

Text
x ^ x = 0
x ^ 0 = x

XOR is also associative and commutative, so array order does not matter.

Java Program

Java
public class UniqueElement {
    public static void main(String[] args) {
        int[] numbers = {6, 4, 9, 4, 6};
        int unique = 0;
        for (int number : numbers) {
            unique ^= number;
        }
        System.out.println("Unique element: " + unique);
    }
}

Program Output

Output
Unique element: 9

Dry Run

Conceptually: 6 ^ 4 ^ 9 ^ 4 ^ 6. Rearrange equal pairs: (6 ^ 6) ^ (4 ^ 4) ^ 9. Therefore: 0 ^ 0 ^ 9 = 9.

Complexity

  • Time: O(n)
  • Space: O(1)

Important Assumption

The XOR solution requires every non-unique value to occur exactly twice. If values can occur arbitrary numbers of times, use frequency counting instead.

Interview Tip

When a problem says "all elements occur twice except one", XOR should be one of the first techniques considered.

12. Find Repeated Elements

Problem

Find elements whose frequency is greater than one and display how many times each repeated value occurs. This differs from simply detecting duplicates because the frequency itself is required.

Example

Input
[5, 8, 5, 2, 8, 8, 4]
Output
5 repeated 2 times
8 repeated 3 times

Logic

A frequency map represents data such as:

Text
5 -> 2
8 -> 3
2 -> 1
4 -> 1

Only entries with frequency greater than 1 are repeated.

Java Program

Java
import java.util.LinkedHashMap;
import java.util.Map;
public class RepeatedElements {
    public static void main(String[] args) {
        int[] numbers = {5, 8, 5, 2, 8, 8, 4};
        Map frequency = new LinkedHashMap<>();
        for (int number : numbers) {
            frequency.put(number, frequency.getOrDefault(number, 0) + 1);
        }
        for (Map.Entry entry : frequency.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.println(entry.getKey() + " repeated " + entry.getValue() + " times");
            }
        }
    }
}

Program Output

Output
5 repeated 2 times
8 repeated 3 times

Why LinkedHashMap?

HashMap does not guarantee insertion order. LinkedHashMap makes the displayed order predictable and follows the order in which distinct values first appear.

Complexity

Average case:

  • Time: O(n)
  • Space: O(n)

Alternative Approach

If values belong to a small known range, an integer frequency array can be faster and lighter than a map.

13. Find Common Elements

Problem

Find distinct elements that appear in both arrays.

Example

Input
First:  [3, 5, 7, 9, 11]
Second: [2, 5, 8, 9, 12]
Output
Common elements: [5, 9]

Logic

Build a lookup set from the first array. For every value in the second array: check whether it exists in the lookup set, and if yes, add it to the result set. A result set prevents duplicate output.

Java Program

Java
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
public class CommonElements {
    public static void main(String[] args) {
        int[] first = {3, 5, 7, 9, 11};
        int[] second = {2, 5, 8, 9, 12};
        Set lookup = new HashSet<>();
        Set common = new LinkedHashSet<>();
        for (int number : first) {
            lookup.add(number);
        }
        for (int number : second) {
            if (lookup.contains(number)) {
                common.add(number);
            }
        }
        System.out.println("Common elements: " + common);
    }
}

Program Output

Output
Common elements: [5, 9]

Dry Run

Lookup after first array: [3, 5, 7, 9, 11]. Check second array: 2 (absent), 5 (present), 8 (absent), 9 (present), 12 (absent). Result: [5, 9].

Complexity

Average case:

  • Time: O(n + m)
  • Space: O(n + k) where k is the number of distinct common values stored in the result.

Alternative for Sorted Arrays

With two sorted arrays, a two-pointer solution can find common elements in O(n + m) without building a full lookup set.

Common Mistake

Nested loops require O(n × m) comparisons and are unnecessary when extra memory is permitted.

14. Find Uncommon Elements

Problem

Find distinct values that occur in exactly one of two arrays. This is the symmetric difference of the two sets.

Example

Input
First:  [1, 2, 3, 4]
Second: [3, 4, 5, 6]
Output
Uncommon elements: [1, 2, 5, 6]

Logic

Create a set for each array. Then: add values from first that are absent from second, and add values from second that are absent from first.

Java Program

Java
import java.util.LinkedHashSet;
import java.util.Set;
public class UncommonElements {
    public static void main(String[] args) {
        int[] first = {1, 2, 3, 4};
        int[] second = {3, 4, 5, 6};
        Set firstSet = new LinkedHashSet<>();
        Set secondSet = new LinkedHashSet<>();
        Set uncommon = new LinkedHashSet<>();
        for (int number : first) {
            firstSet.add(number);
        }
        for (int number : second) {
            secondSet.add(number);
        }
        for (int number : firstSet) {
            if (!secondSet.contains(number)) {
                uncommon.add(number);
            }
        }
        for (int number : secondSet) {
            if (!firstSet.contains(number)) {
                uncommon.add(number);
            }
        }
        System.out.println("Uncommon elements: " + uncommon);
    }
}

Program Output

Output
Uncommon elements: [1, 2, 5, 6]

Dry Run

First set: [1, 2, 3, 4]. Second set: [3, 4, 5, 6]. Only in first: [1, 2]. Only in second: [5, 6]. Combined: [1, 2, 5, 6].

Complexity

Average case:

  • Time: O(n + m)
  • Space: O(n + m)

Important Distinction

Common elements are the intersection: A ∩ B. Uncommon elements are the symmetric difference: values in A or B, but not both.

Linear Search vs Binary Search

FeatureLinear SearchBinary Search
Sorted input requiredNoYes
Basic time complexityO(n)O(log n)
Works naturally on unsorted dataYesNo
Implementation complexitySimpleModerate
Best for small arraysYesYes
Efficient for large sorted arraysLess efficientYes
Random access usefulNot requiredRequired for efficient array implementation

First Occurrence vs Last Occurrence

For a sorted array [2, 4, 4, 4, 4, 8] and target 4, results are:

Text
First occurrence = 1
Last occurrence = 4
Count = 4 - 1 + 1 = 4

The key difference appears after finding the target. For first occurrence: high = mid - 1. For last occurrence: low = mid + 1.

Duplicate, Repeated, and Unique Elements

These terms are related but not identical.

Duplicate Element

A value appearing more than once. Example: [1, 2, 3, 2]. Duplicate: 2.

Multiple Duplicate Elements

Several different values appear more than once. Example: [1, 2, 1, 3, 2, 4]. Duplicates: 1, 2.

Repeated Elements

Usually asks which values occur repeatedly, sometimes together with their frequency. Example: 7 repeated 3 times.

Unique Element

A value satisfying the specific uniqueness condition of the problem. Example: [3, 8, 3]. Unique element: 8. Always read the exact constraints before choosing an algorithm.

Important Search Conditions

Use Linear Search When

  • Array is unsorted.
  • Input is small.
  • Only one search is needed.
  • Sorting would add unnecessary cost.

Use Binary Search When

  • Array is already sorted.
  • Fast repeated searches are needed.
  • Random access is available.
  • The search condition can eliminate half of the remaining range.

Use HashSet When

  • Fast membership checking is required.
  • Duplicate detection is needed.
  • Common or uncommon values are needed.
  • Additional O(n) memory is acceptable.

Use HashMap When

  • Frequency information is needed.
  • Occurrence counts matter.
  • Elements are arbitrary values.

Use XOR When

The problem has a special cancellation pattern such as every value occurring twice except one, or one number missing under appropriate constraints. Do not use XOR blindly when occurrence rules differ.

Common Array Searching Mistakes

1. Using Binary Search on Unsorted Data

Binary search relies on ordering. Without sorting, choosing which half to discard is impossible.

2. Stopping at the First Binary Search Match

This fails when the question asks for first occurrence, last occurrence, or number of occurrences.

3. Ignoring Duplicate Constraints

An algorithm valid for one duplicate may not work when multiple distinct duplicates exist.

4. Using Nested Loops Without Need

For common elements, duplicates, and frequency problems, sets or maps often reduce O(n²) logic to average O(n).

5. Forgetting the Not-Found Case

Search methods commonly use -1 to represent an invalid or missing index.

6. Incorrect Binary Search Loop Condition

Use while (low <= high). Using only low < high can skip the final candidate unless the algorithm is specifically designed around that condition.

7. Incorrect Middle Calculation

Prefer int mid = low + (high - low) / 2; instead of int mid = (low + high) / 2; The first version avoids overflow when indexes are very large.

8. Assuming Set Order

HashSet does not guarantee iteration order. If output order matters, use an appropriate ordered structure such as LinkedHashSet.

9. Applying Arithmetic Missing-Number Logic to Invalid Data

The sum formula assumes a valid consecutive range and exactly one missing element.

10. Ignoring Empty Arrays

Searching an empty array must safely return a not-found result rather than accessing index 0.

Relevant Edge Cases

Array-searching programs should be tested with cases such as:

  • Empty array.
  • Single-element array.
  • Target at first index.
  • Target at last index.
  • Target absent.
  • Every element identical.
  • Negative values.
  • Zero.
  • Duplicate values.
  • Missing value at start of expected range.
  • Missing value at end of expected range.
  • Already sorted data.
  • Rotated but otherwise sorted data.

Only apply edge cases that match the problem's stated constraints.

Interview-Focused Complexity Summary

ProblemPreferred TechniqueTimeExtra Space
Linear SearchSequential traversalO(n)O(1)
Binary SearchDivide search rangeO(log n)O(1)
First OccurrenceModified binary searchO(log n)O(1)
Last OccurrenceModified binary searchO(log n)O(1)
Count OccurrencesTwo boundary searchesO(log n)O(1)
Sorted Array SearchBinary searchO(log n)O(1)
Rotated Array SearchModified binary searchO(log n)O(1)
Missing ElementSum or XORO(n)O(1)
One DuplicateFloyd's cycle detectionO(n)O(1)
Multiple DuplicatesHashSetO(n) averageO(n)
Unique ElementXORO(n)O(1)
Repeated ElementsFrequency mapO(n) averageO(n)
Common ElementsHashSetO(n + m) averageO(n)
Uncommon ElementsSet differenceO(n + m) averageO(n + m)

Problem-Solving Checklist

Before writing code for an array-searching problem, identify:

  1. Is the array sorted?
  2. Can duplicate values occur?
  3. Is one matching index required or every matching value?
  4. Is the first or last occurrence required?
  5. Is frequency information required?
  6. Are array values restricted to a known range?
  7. Can extra memory be used?
  8. Can the original array be modified?
  9. Does the input have a special mathematical property?
  10. What result should represent "not found"?

These details usually determine the correct algorithm before coding begins.

Practice Variations

After understanding the basic problems, useful interview variations include:

  • Implement recursive binary search.
  • Find the insertion position of a target.
  • Find floor and ceiling of a number.
  • Find the smallest element greater than a target.
  • Find the largest element smaller than a target.
  • Search in a descending sorted array.
  • Search in an array with unknown logical size.
  • Find a peak element.
  • Find rotation count of a sorted array.
  • Find the minimum value in a rotated array.
  • Count duplicates without printing them twice.
  • Find two unique values when all others appear twice.
  • Find the missing value using XOR.
  • Find common elements in three sorted arrays.
  • Find intersection while preserving duplicate frequency.
  • Find symmetric difference of two arrays.
  • Search a target in a nearly sorted array.

These variations reuse the core ideas from this chapter while changing the constraints, which is how array-searching questions are commonly made more challenging.

Question Hint