Contains Duplicate Problem Solution Trade-Offs Java LeetCode

LeetCode — But Did You Think About the How? #ContainsDuplicate | NeetCode 150 Most devs solve "Contains Duplicate" - https://lnkd.in/gq84sj37 and move on. But this problem is a great lens for thinking about trade-offs — and that's exactly what interviewers are watching for. Here are my two solutions: Solution 1 — Sort + Linear Scan class Solution { public boolean hasDuplicate(int[] nums) { Arrays.sort(nums); for (int i = 1; i < nums.length; i++) { if (nums[i] == nums[i - 1]) return true; } return false; } } Time: O(n log n) | Space: O(1) (in-place sort) Solution 2 — Stream + Distinct class Solution { public boolean hasDuplicate(int[] nums) { return Arrays.stream(nums).distinct().count() < nums.length; } } Time: O(n) | Space: O(n) My repository - https://lnkd.in/g_Ke_eqR Key Insight: One liner looks cleaner. But it costs you extra memory. The sort-based approach trades time for space — and modifies the original array. Neither is universally "better." The right answer depends on your constraints: → Memory-constrained system? Go with Sort. → Read-only array or immutable input? Stream wins. → Need early exit on first duplicate? Both support it — but stream is lazy, so it does too This is the kind of thinking that separates good developers from great ones in interviews. What's your go-to approach? Drop it below #Java #LeetCode #NeetCode #DSA #CodingInterview #SpringBoot #SoftwareEngineering #ProblemSolving #100DaysOfCode

  • contains-duplicate-sorting-stream

To view or add a comment, sign in

Explore content categories