705148. Pairs of Adjacent elements

Easy

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:

  1. Initialize an empty list result to store the pairs of adjacent elements.
  2. Iterate through the array from left to right.
  3. For each element at index i, calculate its difference with the previous element at index i-1.
  4. If the difference is less than or equal to 1, add the pair (arr[i], arr[i-1]) to the result list.
  5. 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

View on GeeksforGeeks
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] + "]");
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.