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
- Problem Statement
- Complexity Analysis
- N-Repeated Element in Size N Array solution in C++
- N-Repeated Element in Size N Array solution in Java
- N-Repeated Element in Size N Array solution in Python
- Additional Resources
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
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.