705148. Pairs of Adjacent elements
Pairs of Adjacent Elements
Slug: pairs-of-adjacent-elements4814 Difficulty: Easy Id: 705148 Topic Tags: Arrays, Data Structures Company Tags: None
Summary
Given an array of integers, find all pairs of adjacent elements that have a difference of less than or equal to 1. The problem is related to arrays and data structures.
Detailed Explanation
To solve this problem, we can iterate through the array once and keep track of the previous element's value. For each element in the array, check if its difference with the previous element is less than or equal to 1. If it is, add the pair to our result list. Since we're iterating only once and checking adjacent elements, this approach has a linear time complexity.
Here's the step-by-step breakdown of the solution:
- Initialize an empty list
resultto store the pairs of adjacent elements. - Iterate through the array from left to right.
- For each element at index
i, calculate its difference with the previous element at indexi-1. - If the difference is less than or equal to 1, add the pair
(arr[i], arr[i-1])to theresultlist. - Continue this process until the end of the array.
Time complexity: O(n), where n is the length of the input array.
Space complexity: O(n), as we're storing all pairs in the result list.
Optimized Solutions
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static List<int[]> findPairs(int[] arr) {
List<int[]> result = new ArrayList<>();
for (int i = 1; i < arr.length; i++) {
if (Math.abs(arr[i] - arr[i-1]) <= 1) {
result.add(new int[]{arr[i], arr[i-1]});
}
}
return result;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
List<int[]> pairs = findPairs(arr);
for (int[] pair : pairs) {
System.out.println("[" + pair[0] + ", " + pair[1] + "]");
}
}
}