BackeasyHashingAmazonAccenture

Detect Duplicate Packages Solution

Problem Statement

Given a stream of package identifiers and a window size, implement a function to identify duplicate packages within the window. If the window size is not specified, consider the entire array.

Example 1
Input
[1, 2, 3, 1], 3
Output
true

Explanation: Step-by-step: with input [1, 2, 3, 1] and window size 3, we check each package in the window. Since package 1 appears twice within the window, we return true.

Example 2
Input
[1, 2, 3, 4], 2
Output
false

Explanation: Step-by-step: with input [1, 2, 3, 4] and window size 2, we check each package in the window. Since no package appears twice within the window, we return false.

Constraints

  • 1 <= n <= 10^5
  • 0 <= k <= 10^5
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Detect Duplicate Packages — Problem Statement & Solution Guide

HashingEasySliding Window / Hash Map
TimeO(n*m)
|
SpaceO(m)

Problem Description

Given a stream of package identifiers and a window size, implement a function to identify duplicate packages within the window. If the window size is not specified, consider the entire array.

Examples

Example 1

Input

[1, 2, 3, 1], 3

Output

true

Explanation: Step-by-step: with input [1, 2, 3, 1] and window size 3, we check each package in the window. Since package 1 appears twice within the window, we return true.

Example 2

Input

[1, 2, 3, 4], 2

Output

false

Explanation: Step-by-step: with input [1, 2, 3, 4] and window size 2, we check each package in the window. Since no package appears twice within the window, we return false.

Constraints

  • 1 <= n <= 10^5
  • 0 <= k <= 10^5

Optimal Approach & Strategy

Use a hash set to store packages, allowing for constant time complexity O(1) lookup

Brute Force Approach

Check each package in the list to see if it matches the new package

Verified Code Solutions

JavaScript Solution
Time: O(n*m)
function solution(nums, windowSize) {
       if (windowSize === undefined) {
           windowSize = nums.length;
       }
       for (let i = 0; i <= nums.length - windowSize; i++) {
           let window = nums.slice(i, i + windowSize);
           let packageSet = new Set();
           for (let j = 0; j < window.length; j++) {
               if (packageSet.has(window[j])) {
                   return true;
               }
               packageSet.add(window[j]);
           }
       }
       return false;
   }

Asked in Top Tech Interviews

AmazonAccenture

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.