Member-only story

🧑‍💻 LeetCode 0219 — Contains Duplicate II 🔥 (Java & Python)

Leo N
5 min readNov 9, 2024

--

Generated by ChatGPT

LeetCode Problem 219 is one of those staple array questions that really test your understanding of sliding windows, hash maps, and efficient indexing. In this post, we’ll walk through multiple solutions to this problem in Java, examining both the brute-force approach and more optimized solutions using HashMap and Sliding Window with HashSet.

🤔 Problem Statement

Level 🔥 Easy

The Contains Duplicate II problem is described as follows:

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and the absolute difference between i and j is at most k.

In other words, we need to determine if there are any duplicate values in nums that occur within a distance of k from each other.

💡 Solution

✍ Approach 1: Brute Force (Time Complexity: O(n²))

The simplest approach is to compare every element with every other element within the range k. This approach checks each pair of indices (i, j) where j is within a distance of k from i and returns true if any pair is found.

public boolean…

--

--

Leo N
Leo N

Written by Leo N

🇻🇳 🇸🇬 🇲🇾 🇦🇺 🇹🇭 Engineer @ GXS Bank, Singapore | MSc 🎓 | Technical Writer . https://github.com/nphausg

No responses yet