BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Data processing and features48 of 54 in topic

832. Find the repeated id without modifying the list or using extra memory

MediumData processing and features Pro

A list holds n + 1 integer ids, each between 1 and n inclusive. By counting, at least one id must repeat. Exactly one id value is repeated, though it may appear more than twice.

Write find_duplicate(nums) that returns the repeated id. Do not modify the list, and use only a constant amount of extra memory (so no set and no sorting a copy).

Functiondef find_duplicate(nums)

Example 1

Input: find_duplicate([1, 3, 4, 2, 2])

Output: 2

Example 2

Input: find_duplicate([3, 1, 3, 4, 2])

Output: 3

Constraints

  • 2 <= len(nums) <= 100,000
  • 1 <= nums[i] <= len(nums) - 1
Hint 1

Index 0 is never a value, so it is a safe start.

Hint 2

First find a meeting point inside the cycle.

Hint 3

Then walk two pointers at the same speed.

Common mistakes
  • Sorting or marking values in place, which modifies the list.
  • Using a set, which breaks the memory limit.
  • Starting phase two from the meeting point for both pointers.
Understand the idea

The constraint "values are in 1..n" turns the array into a linked structure where nums[i] is the next pointer. A repeated value means two nodes share a successor, which creates a cycle with an entrance at that value. Floyd's algorithm finds a cycle entrance in O(n) time and O(1) memory. The math: if the tail has length a and they meet b steps into a cycle of length c, then a is a multiple of c minus b, so a pointer from the start and one from the meeting point arrive at the entrance together.

Topics
Data processing and features
Similar questions
  • Split a dataset so every class keeps its shareMedium
  • Bin a feature into quantile buckets learned from training dataMedium
  • Frequency-encode a category with a shared bucket for rare and unseen valuesMedium
  • Generate K-fold train and validation index splitsMedium
All Data processing and features problems
Report
832 / 903
Python 3solution.pyPython idle
1
2
3
4
def find_duplicate(nums):
# return the repeated value; O(1) extra memory, do not modify nums
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS