Skip to content

961. N-Repeated Element in Size 2N Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
9
class Solution {
 public:
  int repeatedNTimes(vector<int>& nums) {
    for (int i = 0; i + 2 < nums.size(); ++i)
      if (nums[i] == nums[i + 1] || nums[i] == nums[i + 2])
        return nums[i];
    return nums.back();
  }
};
1
2
3
4
5
6
7
8
class Solution {
  public int repeatedNTimes(int[] nums) {
    for (int i = 0; i + 2 < nums.length; ++i)
      if (nums[i] == nums[i + 1] || nums[i] == nums[i + 2])
        return nums[i];
    return nums[nums.length - 1];
  }
}
1
2
3
4
5
6
class Solution:
  def repeatedNTimes(self, nums: list[int]) -> int:
    for i in range(len(nums) - 2):
      if nums[i] == nums[i + 1] or nums[i] == nums[i + 2]:
        return nums[i]
    return nums[-1]