N-Repeated Element in Size 2N Array


Problem Description

So, you’ve got an array of size 2N, and guess what? One of the elements is just too clingy and decided to show up twice! The task is to find that pesky little number. Imagine you’re at a party, and there’s that one friend who just can’t take a hint and keeps following you around. You need to identify them before they start asking for your snacks!

In more technical terms, given an array nums of size 2N, where one element appears N times, your job is to find that element. Easy peasy, right?

Code Solution


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]

Approach

The approach here is straightforward. The code iterates through the array and checks if the current element is equal to either the next element or the one after that. If it finds a match, it returns that element. If it doesn’t find any matches in the loop, it simply returns the last element. It’s like playing hide and seek, but you already know where the seeker is hiding!

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(N) – The loop runs through the array, making it linear in terms of time.
Space Complexity O(1) – No extra space is used apart from a few variables.

Real-World Example

Imagine you’re at a family reunion, and everyone is supposed to bring a dish. But, of course, Aunt Karen brings her famous potato salad twice because she thinks it’s that good. You need to identify that potato salad as the repeated dish. Just like in the problem, you’re looking for that one dish that’s making a grand entrance twice!

Similar Problems

If you enjoyed this problem, you might want to check out these similar challenges: