Problem
Given an array of unsorted numbers, check if it contains all elements of some given range.
Examples
Example 1:
|
|
Solution
Method 1 -Sorting
Time Complexity – O(nlogn).
Method 2 - Using HashSet
Here is the approach:
- Create a Set: Use a HashSet to store all unique elements from the array.
- Check Range: Iterate over the specified range and check if each element in the range exists in the set.
- Return Result: If all elements in the range are found in the set, return
true
. Otherwise, returnfalse
.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the number of elements in the array.- This is constant for a given range, so it can be considered
O(k)
, wherek = high - low + 1
- This is constant for a given range, so it can be considered
- 🧺 Space complexity:
O(n)
Method 3 - Using array modification
Here is the approach:
-
Adjust Range Calculation:
- The variable
range
is set tohigh - low + 1
to correctly include both boundaries.
- The variable
-
Mark Elements with linear scan:
- For each element in the array, if it falls within the range
[low, high]
, compute its adjusted index asidx = arr[i] - low
. - Use the index to mark the position in
arr[idx]
by making the value at that index negative. This signifies the presence of the element.
- For each element in the array, if it falls within the range
-
Check for Presence:
- Iterate through the first
range
elements and check if every position was marked. - Adjust to avoid
ArrayIndexOutOfBoundsException
by considering only valid indices.
- Iterate through the first
-
Return Result:
- If all elements in the specified range are marked, return
true
. - If any element in the range is not marked, return
false
.
- If all elements in the specified range are marked, return
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)
for aux space