703124. Smaller and Larger
Basic
Smaller and Larger
Slug: smaller-and-larger4005
Difficulty: Basic
Id: 703124
Topic Tags: Arrays, Data Structures
Company Tags: None
Summary
The "Smaller and Larger" problem requires you to find the elements in an array that are both smaller and larger than a given target element. This is a basic algorithmic problem involving arrays and data structures.
Detailed Explanation
To solve this problem, we will iterate through the array once and keep track of the elements that are both smaller and larger than the target element. We can use two pointers, one at the beginning and one at the end of the array, to efficiently find these elements.
Here is a step-by-step breakdown of the solution:
- Initialize three variables:
smaller,larger, andresultarrays. - Iterate through the input array.
- For each element in the array:
- If the current element is smaller than the target, add it to the
smallerarray. - If the current element is larger than the target, add it to the
largerarray.
- If the current element is smaller than the target, add it to the
- Return the
resultarray which contains elements that are both smaller and larger than the target.
Time complexity: O(n), where n is the size of the input array. Space complexity: O(n), as we need to store the result in an array of size n.
Optimized Solutions
Java
public static int[] findSmallerAndLarger(int[] arr, int target) {
int[] smaller = new int[0];
int[] larger = new int[0];
for (int i : arr) {
if (i < target) {
smaller = addToArray(smaller, i);
} else if (i > target) {
larger = addToArray(larger, i);
}
}
return concatArrays(smaller, larger);
}
public static int[] addToArray(int[] arr, int val) {
int[] newArr = new int[arr.length + 1];
System.arraycopy(arr, 0, newArr, 0, arr.length);
newArr[newArr.length - 1] = val;
return newArr;
}
public static int[] concatArrays(int[] arr1, int[] arr2) {
int[] newArr = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, newArr, 0, arr1.length);
System.arraycopy(arr2, 0, newArr, arr1.length, arr2.length);
return newArr;
}