Optimizing Duplicate Check in Arrays with LeetCode 217

Beginning this journey to learn in public and stay consistent with Problem :- Contains Duplicate (LeetCode 217) Problem Statement :- Given an integer array, return true if any value appears at least twice, otherwise return false. Approach 1 :- Brute Force (Nested Loops) i - Compare every element with others ii - Time Complexity:- O(n²) => because of nested loops iii - Simple but inefficient for large inputs class Solution {    public boolean containsDuplicate(int[] nums) {      for (int i = 0; i < nums.length - 1; i++) {        for (int j = i + 1; j < nums.length; j++) {          if (nums[i] == nums[j])            return true;        }      }      return false;    } } Approach 2 :- Optimized (Sorting) Sort array → check adjacent elements Time Complexity:- O(n log n) class Solution {    public boolean containsDuplicate(int[] nums) {      Arrays.sort(nums);     for (int i = 1; i < nums.length; i++) {        if (nums[i] == nums[i - 1])          return true;      }     return false;    } } Key Learning: Start with brute force → then optimize. How would you optimize this further? One problem. Every day. No shortcuts, just consistency. #LeetCode #Java #DSA #CodingChallenge #SoftwareEngineering #Arrays #Sorting

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories