Skip to content

3931. Check Adjacent Digit Differences

Description

You are given a string s consisting of digits.

Return true if the absolute difference between every pair of adjacent digits is at most 2, otherwise return false.

The absolute difference between a and b is defined as abs(a - b).

Β 

Example 1:

Input: s = "132"

Output: true

Explanation:

  • The absolute difference between digits at s[0] and s[1] is abs(1 - 3) = 2.
  • The absolute difference between digits at s[1] and s[2] is abs(3 - 2) = 1.
  • Since both differences are at most 2, the answer is true.

Example 2:

Input: s = "129"

Output: false

Explanation:

  • The absolute difference between digits at s[0] and s[1] is abs(1 - 2) = 1.
  • The absolute difference between digits at s[1] and s[2] is abs(2 - 9) = 7, which is greater than 2.
  • Therefore, the answer is false.

Β 

Constraints:

  • 2 <= s.length <= 100
  • s consists only of digits.

Solutions

Solution 1: Simulation

We can simulate the process described in the problem: iterate through each pair of adjacent digits in the string and compute their absolute difference. If any pair has an absolute difference greater than 2, return \(\text{false}\). If no such pair is found after the traversal, return \(\text{true}\).

The time complexity is \(O(n)\), where \(n\) is the length of the string. The space complexity is \(O(1)\).

1
2
3
class Solution:
    def isAdjacentDiffAtMostTwo(self, s: str) -> bool:
        return all(abs(x - y) <= 2 for x, y in pairwise(map(int, list(s))))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    public boolean isAdjacentDiffAtMostTwo(String s) {
        for (int i = 1; i < s.length(); ++i) {
            if (Math.abs(s.charAt(i - 1) - s.charAt(i)) > 2) {
                return false;
            }
        }
        return true;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
public:
    bool isAdjacentDiffAtMostTwo(string s) {
        for (int i = 1; i < s.size(); ++i) {
            if (abs(s[i - 1] - s[i]) > 2) {
                return false;
            }
        }
        return true;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
func isAdjacentDiffAtMostTwo(s string) bool {
    for i := 1; i < len(s); i++ {
        if abs(int(s[i-1])-int(s[i])) > 2 {
            return false
        }
    }
    return true
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}
1
2
3
4
5
6
7
8
function isAdjacentDiffAtMostTwo(s: string): boolean {
    for (let i = 1; i < s.length; i++) {
        if (Math.abs(Number(s[i]) - Number(s[i - 1])) > 2) {
            return false;
        }
    }
    return true;
}

Comments