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
Optimizing Duplicate Check in Arrays with LeetCode 217
More Relevant Posts
-
🚀 Solved a classic Binary Search problem today: Find Minimum in Rotated Sorted Array 🔍 At first glance, it looks like a sorted array problem. But the rotation adds a twist that tests your ability to spot patterns and optimize search space. 💡 Key Learning: Instead of scanning the entire array, we can use Binary Search to identify which half is sorted and eliminate the other half. This reduces the time complexity from: ❌ Brute Force → O(n) ✅ Optimized Approach → O(log n) Example: [4,5,6,7,0,1,2] Minimum element = 0 📌 Biggest takeaway: Problem solving is not just about coding it’s about recognizing hidden structure inside the data. Every problem has a pattern. The skill is learning how to spot it. 🎯 #Java #DSA #BinarySearch #Leetcode #ProblemSolving #SoftwareEngineer #CodingInterview #BackendDeveloper
To view or add a comment, sign in
-
🚀 LeetCode Problem of the Day 📌 Problem: Minimum Distance to Target Element Given an integer array nums (0-indexed) and two integers target and start, we need to find an index i such that: nums[i] == target |i - start| is minimized 👉 Return the minimum absolute distance. 💡 Key Idea: We simply scan the array and track the minimum distance whenever we find the target. 🧠 Approach Traverse the array Whenever nums[i] == target, compute abs(i - start) Keep updating the minimum result 💻 Java Solution class Solution { public int getMinDistance(int[] nums, int target, int start) { int res = Integer.MAX_VALUE; for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { res = Math.min(res, Math.abs(i - start)); } } return res; } } 📊 Complexity Analysis ⏱ Time Complexity: O(n) → single pass through the array 🧠 Space Complexity: O(1) → no extra space used ⚡ Simple linear scan, optimal solution — sometimes brute force is already the best solution! #LeetCode #Coding #Java #ProblemSolving #DataStructures #Algorithms #InterviewPrep
To view or add a comment, sign in
-
-
🚀 From Brute Force to Optimization — Pair Sum Problem While learning DSA, I explored how a simple problem can be optimized with the right approach. 💡 Problem: Find if any pair in a sorted array has a target sum. 💡 Brute Force: • Check every possible pair • Time Complexity: O(n²) ⚡ Optimization Insight: O(n²) → O(n) 💡 Optimized Approach (Two Pointer): • Start with two pointers at left and right ends • If sum == target → found • If sum < target → move left pointer forward • If sum > target → move right pointer backward • Time Complexity: O(n) This problem helped me understand how choosing the right approach can drastically improve performance. Excited to keep improving problem-solving skills one step at a time 🚀 #DSA #Java #TwoPointer #ProblemSolving #LearningJourney
To view or add a comment, sign in
-
-
🧠 LeetCode POTD — From TLE to Optimized Thinking 3488. Closest Equal Element Queries At first, the approach felt straightforward. For each query: 👉 Start from the given index 👉 Expand left and right (circularly) 👉 Find the closest same element ━━━━━━━━━━━━━━━━━━━ 💥 The problem? This works… but doesn't scale. If there are q queries and n elements: → Each query can take O(n) → Total = O(n × q) 👉 This leads to TLE for large inputs. ━━━━━━━━━━━━━━━━━━━ 💡 So what's the issue? We are repeating the same work again and again for every query. ━━━━━━━━━━━━━━━━━━━ 📌 Better Approach: Preprocess the array. 👉 Use a map: value → list of indices Example: nums = [1, 2, 1, 3, 1] → 1 → [0, 2, 4] Now for each query: Get all indices of that value If only one occurrence → answer = -1 Else: 👉 Use binary search to find the closest index 👉 Check neighbors (left & right) 📌 Since the array is circular: Distance = min(|i - j|, n - |i - j|) ━━━━━━━━━━━━━━━━━━━ 💡 Complexity now: → Preprocessing: O(n) → Each query: O(log n) 👉 Total: O(n + q log n) ━━━━━━━━━━━━━━━━━━━ 📌 What I liked about this problem: The solution isn't complicated. The key is realizing: 👉 "This is not a single query problem." Once you see that, the shift from brute force → optimized becomes obvious. ✅ Sometimes optimization is not about faster code ✅ It's about not repeating the same work Curious if someone solved it differently 👀 #LeetCode #DataStructures #ProblemSolving #SoftwareEngineering #DSA #C++ #Java #SDE
To view or add a comment, sign in
-
-
Hi everyone 👋 Continuing the Spring Boot Validation Series Part 30👇 📌 Validation Annotation – @Pattern The @Pattern annotation is used to validate a field using a regular expression (regex) 👇 🔹 Why do we use @Pattern? Sometimes we need to validate format like: Email format Phone number Password rules Only alphabets / numbers 👉 @Pattern helps enforce these rules. 🔹 Simple Example - public class User { @Pattern(regexp = "^[a-zA-Z]+$") private String name; } 👉 Allows only alphabets 👉 If invalid → validation fails ❌ 🔹 Email Example - @Pattern(regexp = "^[A-Za-z0-9+_.-]+@(.+)$") private String email; 🔹 Important Point 👉 @Pattern works only with String fields 👉 It does NOT check null ❌ So often combined with: @NotNull @Pattern(regexp = "your-regex") private String field; 🔹 In simple words @Pattern checks if a value follows a specific format. 👉 🧠 Quick Understanding - Uses regex for validation - Works only on String - Used for format validation - Often combined with @NotNull or @NotBlank #SpringBoot #Java #Validation #PatternAnnotation #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
📅 Date: April 29, 2026 Day 7 of my LeetCode Journey 🚀 ✅ Problem Solved: 17. Letter Combinations of a Phone Number 🧠 Approach & Smart Solution: Stepping into the world of Recursion! To solve this classic combinatorial problem, I implemented a Backtracking algorithm. Instead of using complex nested loops (which would vary depending on the input length), a recursive helper function elegantly handles the generation of all possible letter combinations. • Pseudo-code: Handle the edge case: If the input string is empty, immediately return an empty list. Create an array to map phone digits (2-9) to their corresponding string of letters. Initialize a recursive 'backtrack' function that takes the current built string and the remaining digits. Base Case: If there are no remaining digits, add the currently built string to the final output list. Recursive Step: Take the first digit from the remaining digits and look up its mapped letters. Loop through each mapped letter: Append the letter to the current string and recursively call the 'backtrack' function with the rest of the digits. This approach beautifully simulates a depth-first search through all possible phone key combinations! ⏱️ Time Complexity: O(4^n * n) (Where 'n' is the length of digits. The worst-case digits like 7 and 9 have 4 letters) 📦 Space Complexity: O(n) (For the recursion call stack depth) 📊 Progress Update: • Streak: 7 Days 🔥 • Difficulty: Medium • Pattern: Backtracking / Recursion 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Mastering backtracking is a massive milestone for tackling complex decision-tree problems in backend logic! 💡 #LeetCode #DSA #Backtracking #Java #Recursion #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
#CodeEveryday — My DSA Journey | Day 2 🧩 Problem Solved: Combination Sum II (LeetCode) 💭 What I Learned: Used backtracking to generate all unique combinations whose sum equals the target. Sorted the array initially to efficiently handle duplicates and enable pruning. At each step: ✔️ Skipped duplicate elements using i > n && nums[i] == nums[i-1] ✔️ Stopped recursion early when the current element exceeded the target ✔️ Moved to the next index (i+1) to avoid reusing elements Strengthened my understanding of handling duplicates in recursion and optimizing search space. ⏱ Time Complexity: O(2ⁿ)*k (k is avg length of each combination) 🧠 Space Complexity: O(n) ⚡ Key Takeaways: ✔️ Sorting helps in both pruning and duplicate handling ✔️ Skipping duplicates is crucial for unique combinations ✔️ Backtracking becomes efficient with early stopping conditions 💻 Language Used: Java ☕ 📘 Concepts: Backtracking · Recursion · Arrays · Duplicate Handling · Pruning #CodeEveryday #DSA #LeetCode #Java #Backtracking #ProblemSolving #Algorithms #CodingJourney #Consistency 🚀
To view or add a comment, sign in
-
-
🚀 #100DaysOfDSA – Day 5 Staying consistent and diving deeper into problem-solving 💪 Today’s problem introduced a powerful technique used in linked lists! 🧩 Problem of the Day: Detect Cycle in a Linked List 🔹 Approach 1: Brute Force (Using Hashing) 👉 Idea: Traverse the linked list Store each node in a HashSet If a node is already visited → cycle exists 🧠 Pseudo Code (Brute Force): Create a HashSet Traverse the list: If node already exists in set → return true Else add node to set If traversal ends → return false 👉 Time Complexity: O(N) 👉 Space Complexity: O(N) ❌ 🔹 Approach 2: Floyd’s Cycle Detection (Tortoise & Hare) 🚀 👉 Idea: Use two pointers: slow moves 1 step fast moves 2 steps If a cycle exists → they will meet If no cycle → fast reaches null 🧠 Pseudo Code (Optimized): Initialize slow = head, fast = head While fast != null and fast.next != null: Move slow by 1 step Move fast by 2 steps If slow == fast → cycle exists Return false 👉 Time Complexity: O(N) 👉 Space Complexity: O(1) ✅ ✅ Java Code: public class Solution { public boolean hasCycle(ListNode head) { ListNode slow = head; ListNode fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) { return true; } } return false; } } 💡 Key Learning: Two pointer technique can solve problems without extra space Floyd’s Algorithm is a must-know for linked list questions Always check fast and fast.next to avoid null pointer issues Enjoying the journey and learning new patterns every day 🔥 On to Day 6 🚀 #DSA #100DaysChallenge #CodingJourney #Java #ProblemSolving #InterviewPrep
To view or add a comment, sign in
-
**Day 109 of #365DaysOfLeetCode Challenge** Today’s problem: **132 Pattern (LeetCode 456)** This problem looks tricky at first because it asks for a hidden subsequence: Find indices `i < j < k` such that: `nums[i] < nums[k] < nums[j]` That forms the **132 pattern** 💡 **Core Idea: Use a Monotonic Stack** Instead of checking all triplets (**O(n³)** ❌), we scan from **right to left**. Why reverse? Because while moving backward: * We try to build possible `3` values using a stack * Track the best possible `2` using a variable called `third` 👉 If we ever find a number smaller than `third`, then: `nums[i] < third < nums[j]` 📌 **Approach:** * Traverse from end to start * Maintain decreasing stack * Pop smaller elements and update `third` * If current number < `third` → return true ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Some array problems become much easier when traversed **backward instead of forward**. 💭 **Key Takeaway:** When the problem asks for hidden order relations: 👉 Think stacks 👉 Think reverse traversal 👉 Think maintaining candidates dynamically This was a great reminder that brute force is rarely the final answer #LeetCode #DSA #MonotonicStack #Arrays #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Day 86 — Prefix Sum Pattern (Introduction) Today I started learning the Prefix Sum pattern — a fundamental technique for array problems where decisions at a given index depend on the sum of previous elements. Unlike sliding window, prefix sum handles negative numbers gracefully. 📌 What is Prefix Sum? At index i, the prefix sum is the sum of all elements from the start up to i-1. It stores “historical information” to make efficient decisions. 🧠 Why Prefix Sum > Sliding Window for Negatives? Sliding window fails with negatives because removing a negative actually increases the sum — breaking the logic of expanding/shrinking. Prefix sum remains effective. 📊 Four Categories of Prefix Sum Problems: 1️⃣ Left‑Right Comparisons (e.g., Pivot Index) → Can often be solved with simple variables (no extra arrays). 2️⃣ Exact Sums (Subarray Sum = K) → Requires a HashMap to store and lookup previous prefix sums. 3️⃣ Shortest Window with Sum ≥ K (with negatives) → Needs a Deque (double‑ended queue). 4️⃣ Range Sum Queries → Advanced techniques like Merge Sort on prefix array. 🔧 General Template: Initialize data structure (variable, array, or HashMap). Loop through the array, updating prefix information. Check problem‑specific condition. ⚡ Optimization Insight (Pivot Index Example): Instead of storing both prefix and suffix arrays, use: Total Sum = Left Sum + arr[i] + Right Sum → Right Sum = Total Sum - Left Sum - arr[i] This finds the pivot using only O(1) space. 💡 Takeaway: Prefix sum is a pattern, not just an algorithm. Recognizing when to use it — especially with negative numbers — unlocks efficient solutions for subarray sum problems. No guilt about past breaks — just adding another powerful pattern to the toolkit. #DSA #PrefixSum #ArrayPatterns #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development