Maximum Difference Between Adjacent Elements in a Circular Array - Problem
Maximum Difference Between Adjacent Elements in a Circular Array

You're given a circular array nums, where the last element connects back to the first element, forming a complete circle. Your task is to find the maximum absolute difference between any two adjacent elements in this circular structure.

Think of this array as a circle of numbers where each number has exactly two neighbors - the one before it and the one after it. The special property of a circular array is that the first and last elements are considered adjacent to each other.

Goal: Return the largest absolute difference between any pair of adjacent elements.

Example: For array [1, 3, 7, 1], the adjacent pairs are: (1,3), (3,7), (7,1), and (1,1). The differences are |1-3|=2, |3-7|=4, |7-1|=6, |1-1|=0. The maximum is 6.

Input & Output

example_1.py โ€” Python
$ Input: nums = [1, 3, 7, 1]
โ€บ Output: 6
๐Ÿ’ก Note: The adjacent pairs are (1,3), (3,7), (7,1), and (1,1) due to circular nature. Their absolute differences are 2, 4, 6, and 0 respectively. The maximum is 6.
example_2.py โ€” Python
$ Input: nums = [5, 5, 5, 5]
โ€บ Output: 0
๐Ÿ’ก Note: All elements are the same, so all adjacent differences are 0. The maximum difference is 0.
example_3.py โ€” Python
$ Input: nums = [1, 100]
โ€บ Output: 99
๐Ÿ’ก Note: In a circular array of 2 elements, both pairs (1,100) and (100,1) have the same absolute difference of 99.

Constraints

  • 1 โ‰ค nums.length โ‰ค 103
  • -109 โ‰ค nums[i] โ‰ค 109
  • The array is treated as circular - first and last elements are adjacent

Visualization

Tap to expand
1Position 03Position 17Position 21Position 3|1-3|=2|3-7|=4|7-1|=6 (MAX!)|1-1|=0Maximum Adjacent Difference = 6
Understanding the Visualization
1
Start at Position 0
Begin at the first element and prepare to check all adjacent pairs
2
Check Each Adjacent Pair
For each position i, calculate |nums[i] - nums[(i+1) % n]|
3
Track Maximum
Keep updating the maximum difference as you find larger values
4
Complete the Circle
The last element connects back to the first, completing the circular check
Key Takeaway
๐ŸŽฏ Key Insight: In a circular array, every element has exactly two neighbors, and the modulo operator (%) elegantly handles the wraparound from the last element back to the first.
Asked in
Google 25 Amazon 18 Microsoft 12 Apple 8
28.4K Views
Medium Frequency
~12 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen