Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Array Repeat With Complexity

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Array Repeat With Complexity. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Avensys Consulting UK may process ordered numeric sequences where the earliest repeated value must be identified quickly. Implement find_first_repeated for two scenarios and return the number whose second occurrence appears first.

  1. General scenario: nums may contain any integers, and the input must not be modified. Minimize time complexity.
  2. Constant-space scenario: when constant_space is True, nums has length n, contains integers in the range 1 through n, and may be modified. Use the array itself to achieve constant auxiliary space.

Return None if no value is repeated. The function must return the first repeated value according to scan order. For example, in [4, 2, 5, 4, 2], return 4 because its second occurrence is encountered first.

Formal Specification

  • Input: nums, a list of integers, and constant_space, a Boolean.
  • Output: the first repeated integer, or None.
  • If constant_space is False, preserve nums and use expected O(n) time.
  • If constant_space is True, mutation is allowed and extra space must be O(1).

Constraints

  • 0 <= len(nums) <= 100,000
  • General mode allows values from -10^9 through 10^9
  • Constant-space mode requires 1 <= nums[i] <= len(nums)
  • Constant-space mode permits mutation of nums
  • Return the value whose second occurrence appears earliest

Function Signature

def find_first_repeated(nums, constant_space):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output