703453. Search array with adjacent diff at most k

Easy

Search array with adjacent diff at most k

Summary

This problem is about searching for an element in an array where each adjacent pair of elements differs by at most a certain value k. The goal is to find the target element in the array efficiently.

Detailed Explanation

To solve this problem, we can use a two-pointer technique. We start with two pointers, i and j, initially set to 0. We then iterate through the array, moving the pointer that points to the smaller value towards the other end of the array. The key insight is that if the difference between adjacent elements is more than k, we can safely move the pointer that points to the larger value.

Here's a step-by-step breakdown:

  1. Initialize two pointers i and j to 0.
  2. While i is less than j + k, do the following:
    • If the difference between arr[i] and arr[j] is more than k, move j towards i.
    • Otherwise, if target is equal to arr[j], return j. This means we've found the target element.
  3. If we reach the end of the array without finding the target, return -1.

Time complexity: O(n), where n is the length of the array. Space complexity: O(1).

Optimized Solutions

Java

View on GeeksforGeeks
public int search(int[] arr, int target) {
    int i = 0, j = 0;
    while (j + k <= arr.length && i < j + k) {
        if (Math.abs(arr[i] - arr[j]) > k) {
            j++;
        } else if (arr[j] == target) {
            return j;
        }
        i++;
    }
    return -1;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.