You are given an integer array nums with the following properties:
nums.length == 2 * n.nums contains n + 1 unique elements.nums is repeated n times.Return the element that is repeated n times.
Example 1:
Input: nums = [1,2,3,3] Output: 3
Example 2:
Input: nums = [2,1,2,5,3,2] Output: 2
Example 3:
Input: nums = [5,1,5,2,5,3,5,4] Output: 5
Constraints:
2 <= n <= 5000nums.length == 2 * n0 <= nums[i] <= 104nums contains n + 1 unique elements and one of them is repeated exactly n times.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Compare every pair of positions until two of them hold the same value. Every other value appears only once, so the first match is the value repeated N times. Return that value as soon as the match is found.
Here's how the algorithm would work step-by-step:
def repeatedNTimes(numbers):
# This outer loop selects an element to compare against all subsequent elements.
for first_pointer_index in range(len(numbers)):
# This inner loop checks every element after the one selected by the outer loop.
for second_pointer_index in range(first_pointer_index + 1, len(numbers)):
# If two distinct elements at different indices are identical, we have found the repeated number.
if numbers[first_pointer_index] == numbers[second_pointer_index]:
return numbers[first_pointer_index]Remember each value the first time it appears. The moment a value shows up that was already remembered, it is the one repeated N times, because every other value appears only once. Return that value and stop.
Here's how the algorithm would work step-by-step:
def repeated_n_times(numbers_list):
# This collection will store the unique numbers we have encountered.
seen_numbers = set()
for current_number in numbers_list:
# Check if the number is already in our collection of seen numbers.
if current_number in seen_numbers:
# If we find a number we've already seen, it must be the one repeated N times.
return current_number
# If this is the first time seeing the number, add it to our collection.
seen_numbers.add(current_number)| Case | How to Handle |
|---|---|
| The array holds two identical numbers | Both positions hold the repeated value, so that value is returned. |
| The repeated value is zero | Zero is a real value and is returned when it is seen again. |
| The repeated value is negative | Equality still identifies the repeated value, so the sign does not change the result. |
| The copies are not next to each other | The search compares later positions as well, so a distant copy is still found. |
| Many unique values come before the repeat | Those unique values are passed over until the value that occurs again is reached. |