DDSA Solutions

Elements in the Range

Advertisement

Intuition

The current solution counts how many array values fall inside [start, end] after sorting. It then compares this count with the target range length (end-start+1). Under this implementation logic, matching counts are treated as complete coverage.

Algorithm

  1. 1Sort the input array in non-decreasing order.
  2. 2Initialise count = 0.
  3. 3Traverse each value x in arr:
  4. 4 If start <= x <= end, increment count.
  5. 5After traversal, return count == (end - start + 1).

Example Walkthrough

Input: start = 2, end = 4, arr = [5, 2, 3, 4, 8]

  1. 1.Sort arr -> [2, 3, 4, 5, 8].
  2. 2.Values in [2,4] are 2, 3, 4, so count = 3.
  3. 3.Range length is end-start+1 = 3, so function returns true.

Output: true

Common Pitfalls

  • This count-based check can produce false positives when duplicates exist and some value in the range is missing.
  • Sorting is not required for counting alone; it adds O(n log n) time.
  • Handle invalid ranges (start > end) explicitly if problem constraints allow them.
Elements in the Range.java
Java
import java.util.*;

// Approach: Sort the array, then count how many elements lie in [start, end].
// If this count equals (end - start + 1), the range length is fully covered according to this logic.
// Time: O(n log n) Space: O(1) excluding sort stack/internal implementation

class Solution {

    public boolean checkElements(int start, int end, int[] arr) {
        Arrays.sort(arr);
        int count = 0;
        for (int i : arr) {
            if (i >= start && i <= end) {
                count++;
            }
        }
        return count == (end - start + 1);
    }
}
Advertisement
Was this solution helpful?