Algorithm


Problem Name: 961. N-Repeated Element in Size 2N 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.

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
  public int repeatedNTimes(int[] nums) {
    for (int i = 1; i  < = 3; i++) {
      for (int j = 0; j  <  nums.length - i; j++) {
        if (nums[j] == nums[j + i]) {
          return nums[j];
        }
      }
    }
    return -1;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [1,2,3,3]

Output

x
+
cmd
3

#2 Code Example with Javascript Programming

Code - Javascript Programming


const repeatedNTimes = function(A) {
    const checkerSet = new Set();
    for (let num of A){
        if (!checkerSet.has(num)){
            checkerSet.add(num);
        } else{
            return num;
        }
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [1,2,3,3]

Output

x
+
cmd
3

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def repeatedNTimes(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        return collections.Counter(A).most_common(1)[0][0]
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [2,1,2,5,3,2]

Output

x
+
cmd
2

#4 Code Example with C# Programming

Code - C# Programming


using System.Collections.Generic;

namespace LeetCode
{
    public class _0961_NRepeatedElementInSize2NArray
    {
        public int RepeatedNTimes(int[] A)
        {
            var set = new HashSet < int>();
            foreach (var num in A)
            {
                if (set.Contains(num))
                    return num;
                else
                    set.Add(num);
            }

            return -1;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [2,1,2,5,3,2]

Output

x
+
cmd
2
Advertisements

Demonstration


Previous
#960 Leetcode Delete Columns to Make Sorted III Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#962 Leetcode Maximum Width Ramp Solution in C, C++, Java, JavaScript, Python, C# Leetcode