961. N-Repeated Element in Size 2N Array LeetCode Solution

In this guide, you will get 961. N-Repeated Element in Size 2N Array LeetCode Solution with the best time and space complexity. The solution to N-Repeated Element in Size N Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. N-Repeated Element in Size N Array solution in C++
  4. N-Repeated Element in Size N Array solution in Java
  5. N-Repeated Element in Size N Array solution in Python
  6. Additional Resources
961. N-Repeated Element in Size 2N Array LeetCode Solution image

Problem Statement of N-Repeated Element in Size N Array

You are given an integer array nums with the following properties:

nums.length == 2 * n.
nums contains n + 1 unique elements.
Exactly one element of 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 <= 5000
nums.length == 2 * n
0 <= nums[i] <= 104
nums contains n + 1 unique elements and one of them is repeated exactly n times.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

961. N-Repeated Element in Size 2N Array LeetCode Solution in C++

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();
  }
};
/* code provided by PROGIEZ */

961. N-Repeated Element in Size 2N Array LeetCode Solution in Java

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];
  }
}
// code provided by PROGIEZ

961. N-Repeated Element in Size 2N Array LeetCode Solution in Python

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]
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.