Bird
Raised Fist0
DSA Javaprogramming~20 mins

Count Occurrences of Element in Sorted Array in DSA Java - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Count Occurrences Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of counting occurrences using binary search
What is the output of the following Java code that counts occurrences of 3 in a sorted array?
DSA Java
public class CountOccurrences {
    public static int countOccurrences(int[] arr, int x) {
        int first = firstOccurrence(arr, x);
        if (first == -1) return 0;
        int last = lastOccurrence(arr, x);
        return last - first + 1;
    }

    private static int firstOccurrence(int[] arr, int x) {
        int low = 0, high = arr.length - 1, result = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == x) {
                result = mid;
                high = mid - 1;
            } else if (arr[mid] < x) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return result;
    }

    private static int lastOccurrence(int[] arr, int x) {
        int low = 0, high = arr.length - 1, result = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == x) {
                result = mid;
                low = mid + 1;
            } else if (arr[mid] < x) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 3, 3, 4, 5};
        System.out.println(countOccurrences(arr, 3));
    }
}
A1
B2
C0
D3
Attempts:
2 left
💡 Hint
Count how many times 3 appears consecutively in the sorted array.
🧠 Conceptual
intermediate
1:30remaining
Understanding the time complexity of counting occurrences
What is the time complexity of counting occurrences of an element in a sorted array using binary search for first and last occurrences?
AO(n log n)
BO(n)
CO(log n)
DO(1)
Attempts:
2 left
💡 Hint
Binary search divides the search space in half each step.
🔧 Debug
advanced
2:00remaining
Identify the error in counting occurrences code
What error will the following code produce when counting occurrences of 7 in the array?
DSA Java
public class CountOccurrencesBug {
    public static int countOccurrences(int[] arr, int x) {
        int first = firstOccurrence(arr, x);
        int last = lastOccurrence(arr, x);
        return last - first + 1;
    }

    private static int firstOccurrence(int[] arr, int x) {
        int low = 0, high = arr.length - 1, result = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == x) {
                result = mid;
                high = mid - 1;
            } else if (arr[mid] < x) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return result;
    }

    private static int lastOccurrence(int[] arr, int x) {
        int low = 0, high = arr.length - 1, result = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == x) {
                result = mid;
                low = mid + 1;
            } else if (arr[mid] < x) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 3, 3, 4, 5};
        System.out.println(countOccurrences(arr, 7));
    }
}
AReturns 1
BReturns -1
CReturns 0
DThrows ArrayIndexOutOfBoundsException
Attempts:
2 left
💡 Hint
Check what happens when the element is not found in the array.
❓ Predict Output
advanced
2:00remaining
Output of counting occurrences with duplicates at edges
What is the output of the code counting occurrences of 2 in the array?
DSA Java
public class CountOccurrencesEdges {
    public static int countOccurrences(int[] arr, int x) {
        int first = firstOccurrence(arr, x);
        if (first == -1) return 0;
        int last = lastOccurrence(arr, x);
        return last - first + 1;
    }

    private static int firstOccurrence(int[] arr, int x) {
        int low = 0, high = arr.length - 1, result = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == x) {
                result = mid;
                high = mid - 1;
            } else if (arr[mid] < x) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return result;
    }

    private static int lastOccurrence(int[] arr, int x) {
        int low = 0, high = arr.length - 1, result = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == x) {
                result = mid;
                low = mid + 1;
            } else if (arr[mid] < x) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] arr = {2, 2, 2, 3, 4, 5, 6};
        System.out.println(countOccurrences(arr, 2));
    }
}
A3
B2
C1
D0
Attempts:
2 left
💡 Hint
Count how many times 2 appears at the start of the array.
🧠 Conceptual
expert
1:30remaining
Why binary search is preferred over linear scan for counting occurrences in sorted arrays
Why is binary search a better approach than a linear scan to count occurrences of an element in a sorted array?
ABinary search uses less memory than linear scan.
BBinary search reduces time complexity from O(n) to O(log n), making it faster for large arrays.
CLinear scan cannot find the element if it appears multiple times.
DBinary search works only on unsorted arrays, making it more versatile.
Attempts:
2 left
💡 Hint
Think about how many elements each method checks in the worst case.

Practice

(1/5)
1. What is the main advantage of using binary search to count occurrences of an element in a sorted array?
easy
A. It uses less memory than linear search
B. It reduces the search time to logarithmic complexity
C. It sorts the array automatically
D. It works only for unsorted arrays

Solution

  1. Step 1: Understand binary search efficiency

    Binary search divides the search space in half each time, making it faster than checking every element.
  2. Step 2: Compare with linear search

    Linear search checks each element one by one, which takes longer for large arrays.
  3. Final Answer:

    It reduces the search time to logarithmic complexity -> Option B
  4. Quick Check:

    Binary search = O(log n) time [OK]
Hint: Binary search halves search space each step [OK]
Common Mistakes:
  • Thinking binary search sorts the array
  • Confusing memory use with speed
  • Assuming binary search works on unsorted arrays
2. Which Java method signature correctly represents a function to count occurrences of an integer target in a sorted array arr?
easy
A. public static int countOccurrences(int[] arr, int target)
B. public int countOccurrences(int target, int[] arr)
C. static void countOccurrences(int[] arr, int target)
D. int countOccurrences(int[] arr, int target)

Solution

  1. Step 1: Check method return type and parameters

    The method should return an integer count and accept an integer array and target integer as parameters.
  2. Step 2: Verify static and access modifiers

    Static is common for utility methods; public allows access. The order of parameters matters for clarity.
  3. Final Answer:

    public static int countOccurrences(int[] arr, int target) -> Option A
  4. Quick Check:

    Correct signature returns int and takes (int[], int) [OK]
Hint: Return count as int, parameters: array then target [OK]
Common Mistakes:
  • Wrong parameter order
  • Void return type instead of int
  • Missing static keyword when needed
3. What is the output of the following Java code snippet?
int[] arr = {1, 2, 2, 2, 3, 4, 5};
int target = 2;
int count = countOccurrences(arr, target);
System.out.println(count);

public static int countOccurrences(int[] arr, int target) {
    int first = firstOccurrence(arr, target);
    if (first == -1) return 0;
    int last = lastOccurrence(arr, target);
    return last - first + 1;
}

public static int firstOccurrence(int[] arr, int target) {
    int low = 0, high = arr.length - 1, result = -1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == target) {
            result = mid;
            high = mid - 1;
        } else if (arr[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return result;
}

public static int lastOccurrence(int[] arr, int target) {
    int low = 0, high = arr.length - 1, result = -1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == target) {
            result = mid;
            low = mid + 1;
        } else if (arr[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return result;
}
medium
A. 2
B. 4
C. 3
D. 0

Solution

  1. Step 1: Find first occurrence of 2 in array

    First occurrence is at index 1 (arr[1] = 2).
  2. Step 2: Find last occurrence of 2 in array

    Last occurrence is at index 3 (arr[3] = 2).
  3. Step 3: Calculate count

    Count = last - first + 1 = 3 - 1 + 1 = 3.
  4. Final Answer:

    3 -> Option C
  5. Quick Check:

    Occurrences of 2 = 3 [OK]
Hint: Count = last index - first index + 1 [OK]
Common Mistakes:
  • Confusing first and last indices
  • Off-by-one errors in count calculation
  • Returning 0 when element exists
4. Identify the bug in the following method that counts occurrences of target in a sorted array arr:
public static int countOccurrences(int[] arr, int target) {
    int low = 0, high = arr.length - 1;
    int count = 0;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == target) {
            count++;
            low = mid + 1;
        } else if (arr[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return count;
}
medium
A. It counts only occurrences after the first found index
B. It counts only one occurrence instead of all
C. It counts duplicates multiple times incorrectly
D. It never terminates due to infinite loop

Solution

  1. Step 1: Analyze counting logic in binary search

    The code increments count only when arr[mid] == target and moves low to mid + 1, skipping elements before mid.
  2. Step 2: Understand missed occurrences

    This approach counts occurrences only from the first found index forward, missing any before mid.
  3. Final Answer:

    It counts only occurrences after the first found index -> Option A
  4. Quick Check:

    Counting misses earlier duplicates [OK]
Hint: Counting inside binary search loop misses earlier matches [OK]
Common Mistakes:
  • Assuming count increments all occurrences
  • Not updating low/high correctly
  • Expecting binary search to count all duplicates directly
5. Given a sorted array arr that may contain multiple occurrences of target, how can you efficiently count the occurrences if the array is very large and you want to minimize the number of comparisons?
hard
A. Use a hash map to store counts of all elements
B. Use a linear scan from start to end counting matches
C. Sort the array first, then count occurrences
D. Use two binary searches to find first and last occurrence, then subtract indices

Solution

  1. Step 1: Understand the problem constraints

    Array is sorted and large, so linear scan is costly and sorting again is unnecessary.
  2. Step 2: Apply binary search twice

    Use binary search to find the first occurrence index and last occurrence index of target efficiently.
  3. Step 3: Calculate count

    Count = last occurrence index - first occurrence index + 1, minimizing comparisons.
  4. Final Answer:

    Use two binary searches to find first and last occurrence, then subtract indices -> Option D
  5. Quick Check:

    Two binary searches = efficient counting [OK]
Hint: Find first and last index with binary search [OK]
Common Mistakes:
  • Using linear scan on large arrays
  • Sorting already sorted array again
  • Using extra memory unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard