LeetCode 'Contains Duplicate' Problem Solved with Java Sorting

🚀 Day 12 of My DSA Journey Today I solved the “Contains Duplicate” problem on LeetCode using Java. 💡 Problem Statement Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. Example: Input: [1,2,3,1] Output: true Because the value 1 appears more than once. ⚙️ Approach I Used I solved this problem using sorting. Steps: 1️⃣ First, I sorted the array using Arrays.sort() 2️⃣ Then I traversed the array once 3️⃣ Compared each element with the next element 4️⃣ If nums[i] == nums[i+1], it means a duplicate exists → return true 5️⃣ If no duplicates are found, return false 📊 Complexity Analysis Time Complexity: O(n log n) → due to sorting Space Complexity: O(1) (ignoring sorting internal space) 📚 Key Learning Even simple problems can be solved in multiple ways. Sorting helped reduce the problem to a simple adjacent comparison. In future, I’ll also explore a HashSet approach which can solve this in O(n) time. Another day of improving problem-solving skills and algorithmic thinking. On to Day 13 tomorrow. 💪 #DSA #LeetCode #100DaysOfCode #Java #ProblemSolving #CodingJourney #Algorithms #LearningInPublic #Consistency

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories