217. Check If Array Can Converge To Same Value
Asked in
Check If Array Can Converge To Same Value
You are given a list of digits where every value is from 0 to 9. For each index, you may perform exactly one of these choices: add 1, subtract 1 or keep the value unchanged.
The digits are circular, so 9 + 1 = 0 and 0 - 1 = 9. Determine whether all elements can become the same digit after applying at most one such operation to each element.
If convergence is possible, return the final digit. If more than one final digit is possible, return the smallest such digit. If convergence is not possible, return -1.

Method Signature

int findConvergedValue(List<Integer> nums)

Parameters

  • nums: a list of digits.
  • Each element of nums is between 0 and 9.

Returns

  • Return the smallest digit to which all elements can converge.
  • Return -1 if no such digit exists.

Allowed Operation For One Element

  • x may become x.
  • x may become (x + 1) % 10.
  • x may become (x + 9) % 10, which is equivalent to x - 1 circularly.

Constraints

  • 1 ≤ nums.size() ≤ 100,000
  • 0 ≤ nums[i] ≤ 9

Examples

Example 1

findConvergedValue(nums = List.of(2, 3, 2, 1))
Output: 2
Explanation: 3 can become 2, 1 can become 2, and the existing 2 values can stay unchanged.

Example 2

findConvergedValue(nums = List.of(8, 9, 0))
Output: 9
Explanation: 8 can become 9, 9 can stay unchanged, and 0 can become 9 using circular subtraction.

Example 3

findConvergedValue(nums = List.of(1, 4, 2))
Output: -1
Explanation: There is no single digit that all three values can become using at most one operation each.

Example 4

findConvergedValue(nums = List.of(0, 9))
Output: 0
Explanation: Both 0 and 9 are possible convergence values, so the smaller digit 0 is returned.


Please use Laptop/Desktop or any other large screen to add/edit code.