Problem :- Two Sum (LeetCode 1) Problem Statement :- Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to the target. Assume exactly one solution exists, and you may not use the same element twice. Approach 1 :- Brute Force => Nested Loop i - Check every pair of elements ii - If nums[i] + nums[j] == target => return indices iii - Time Complexity : O(n²) class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[]{}; } } Approach 2 :- Optimal => HashMap i - Store number and its index in a HashMap ii - For each element, check if (target - current) exists iii - Time Complexity : O(n) class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[]{map.get(complement), i}; } map.put(nums[i], i); } return new int[]{}; } } Key Takeaway :- Instead of checking every pair, we store previously seen elements and directly find the required complement efficiently. #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #HashMap
Two Sum Problem Solution with Brute Force and HashMap Approaches
More Relevant Posts
-
Day16:- Arrays A Journey with Frontlines EduTech (FLM) and Fayaz S ✒️An array in Java is a data structure used to store multiple values of the same data type in a single variable. ✒️Instead of creating many variables, we store them in one array. Without array:- int a = 10; int b = 20; int c = 30; With array:- int [] numbers = {10,20,30}; Syntax:- dataType[] = new new dataType [size]; Array Initialization and access:- ✒️Arrays can also be initialized with values directly. int[] num = {1,2,3,4,5}; ✒️You can access elements using their index (string Index 0) Looping through arrays:- ✒️You can use loops to traverse arrays. ✒️ Commonly using for or enhanced for loops. ex:- int [] arr = {10,20,30,}; for(int i = 0; i<arr.lenght; i++) { System.out.println(arr[i]); } Advantages of Arrays:- ✒️Arrays allow random access of elements using index. ✒️Arrays are easy to traverse and manipulate using loops. ✒️Arrays help in efficient memory allocation when the size is known. ✒️They store multiple values in a single variable, reducing code complexity. ✒️Arrays are faster in accessing and modifying data compared to some data structures. Two-Dimensional Arrays :- ✒️2D arrays are arrays of arrays. They are useful for matrix-like data representation. Syntax:- dataType[][] arrayName = new dataType[rows][columns]; #arrays #corejava #java #2darrays
To view or add a comment, sign in
-
-
🚀 Day 23/40 – DSA Challenge 📌 LeetCode Problem – Remove Duplicates from Sorted List 📝 Problem Statement Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the modified linked list. 📌 Example Input: 1 → 1 → 2 → 3 → 3 Output: 1 → 2 → 3 💡 Key Insight Since the list is sorted, 👉 duplicates will always be adjacent. So we don’t need extra space or hashing. 🔥 Optimal Approach – Single Traversal 🧠 Idea Traverse the list and compare: Current node Next node If they are equal → skip the next node Else → move forward 🚀 Algorithm 1️⃣ Start from head 2️⃣ While current != null && current.next != null 3️⃣ If: current.val == current.next.val 👉 Skip duplicate: current.next = current.next.next 4️⃣ Else: Move to next node ✅ Java Code (Optimal O(n)) class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode current = head; while (current != null && current.next != null) { if (current.val == current.next.val) { current.next = current.next.next; } else { current = current.next; } } return head; } } ⏱ Complexity Time Complexity: O(n) Space Complexity: O(1) 📚 Key Learnings – Day 23 ✔ Sorted data simplifies problems ✔ Linked list manipulation requires careful pointer handling ✔ No extra space needed when duplicates are adjacent ✔ Always check current.next != null to avoid errors Simple structure. Clean pointer logic. Efficient solution. Day 23 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #LinkedList #LeetCode
To view or add a comment, sign in
-
-
Day 95 of #365DaysOfLeetCode Challenge Today’s problem: **Path Sum III (LeetCode 437)** This one looks like a typical tree problem… but the optimal solution introduces a powerful concept: **Prefix Sum + HashMap in Trees** 💡 **Core Idea:** Instead of checking every possible path (which would be slow), we track **running sums** as we traverse the tree. 👉 If at any point: `currentSum - targetSum` exists in our map → we’ve found a valid path! 📌 **Approach:** * Use DFS to traverse the tree * Maintain a running `currSum` * Store prefix sums in a HashMap * Check how many times `(currSum - targetSum)` has appeared * Backtrack to maintain correct state ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Prefix Sum isn’t just for arrays — it can be **beautifully extended to trees**. This problem completely changed how I look at tree path problems: 👉 From brute-force traversal → to optimized prefix tracking 💭 **Key takeaway:** When a problem involves “subarray/paths with a given sum,” think: ➡️ Prefix Sum + HashMap #LeetCode #DSA #BinaryTree #PrefixSum #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
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
-
**Day 113 of #365DaysOfLeetCode Challenge** Today’s problem: **Contiguous Array (LeetCode 525)** We need to find the **longest contiguous subarray** with an equal number of `0`s and `1`s. At first glance, it feels like a sliding window problem… but the real solution is: 👉 **Prefix Sum + HashMap** 💡 **Core Idea:** Convert: * `0 → -1` * `1 → +1` Now the problem becomes: 👉 Find the longest subarray whose sum = `0` Because equal number of `0`s and `1`s cancel each other out. 📌 **Approach:** 1️⃣ Maintain running sum 2️⃣ Store first occurrence of each sum in HashMap 3️⃣ If same sum appears again: * Subarray between those indices has sum `0` 4️⃣ Maximize length 💡 Why store first occurrence only? Because earliest index gives the **longest possible subarray** ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Many binary array problems can be transformed into prefix sum problems by clever value mapping. 💭 **Key Takeaway:** When asked: * Equal 0s and 1s * Balanced values * Longest valid subarray Think: 👉 Prefix Sum 👉 HashMap 👉 First occurrence trick #LeetCode #DSA #PrefixSum #HashMap #Arrays #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
Problem :- Merge Sorted Array (LeetCode 88) Problem Statement :- You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n representing the number of elements in nums1 and nums2 respectively. Merge nums2 into nums1 as one sorted array. The final sorted array should not be returned, but instead be stored inside nums1. Approach :- Three Pointer Technique i - Use three pointers: i → last element of nums1 (m-1) j → last element of nums2 (n-1) k → last position of nums1 (m+n-1) ii - Compare nums1[i] and nums2[j], place larger at nums1[k] iii - Move pointers accordingly iv - If elements left in nums2, copy them v - Time Complexity : O(m + n) vi - Space Complexity : O(1) class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int p1 = m -1; int p2 = n -1; int p = m + n -1; while(p1 >=0 && p2 >= 0){ if(nums1[p1] > nums2[p2]){ nums1[p] = nums1[p1]; p1--; }else { nums1[p] = nums2[p2]; p2--; } p--; } while (p2 >= 0){ nums1[p] = nums2[p2]; p2--; p--; } } } Key Takeaway :- Instead of merging from the front (which causes shifting), start from the end and place elements in correct position using three pointers. How would you optimize this further? Is there any way to handle merging without using extra space in other variations? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #TwoPointers
To view or add a comment, sign in
-
-
🔥 Day 552 of #750DaysOfCode 🔥 🔐 LeetCode 2075: Decode the Slanted Ciphertext (Medium) Today’s problem looked tricky at first, but once the pattern clicked, it became super elegant 😄 🧠 Problem Understanding We are given an encoded string that was: Filled diagonally (↘) into a matrix Then read row-wise (→) 👉 Our task is to reverse this process and recover the original text. 💡 Key Insight If encoding is: ➡️ Fill diagonally ➡️ Read row-wise Then decoding is: ➡️ Read diagonally from row-wise string ⚙️ Approach ✅ Step 1: Calculate number of columns cols = encodedText.length() / rows; ✅ Step 2: Traverse diagonals starting from each column for (int startCol = 0; startCol < cols; startCol++) { int row = 0, col = startCol; while (row < rows && col < cols) { result.append(encodedText.charAt(row * cols + col)); row++; col++; } } ✅ Step 3: Remove trailing spaces 🚀 Complexity Time: O(n) Space: O(n) 🧠 What I Learned How to reverse matrix-based encoding patterns Converting 2D traversal → 1D index mapping Importance of pattern recognition in problems 📌 Takeaway Not every problem needs heavy logic. Sometimes, it's just about seeing the pattern correctly 👀 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Algorithms #SoftwareEngineering #100DaysOfCode #750DaysOfCode
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
-
-
🚀 Day 11 — Streams, Partitioned Logs, and Consumer Groups Queues are useful when work needs to be processed asynchronously. But Day 11 helped me understand a different pattern: 👉 when events need to be stored, replayed, and consumed by multiple independent systems. That is where streams and partitioned logs become important. Because in event-driven systems, data is not just passed from one service to another. It becomes a continuous flow that different consumers may process in different ways. Today’s focus was: Streams, Partitioned Logs, and Consumer Groups 📊 What I covered today 📘 📜 Append-only event logs 🧩 Partitioning for scale 🔑 Ordering guarantees and key-based routing 👥 Consumer groups and offset tracking 🔁 Replay and recovery 📉 Lag monitoring and backpressure What stood out to me ✅ Append-only logs make replay, auditing, and recovery much easier ✅ Partitioning improves throughput, but ordering is only guaranteed within a partition ✅ Key-based routing helps keep related events together ✅ Consumer groups allow multiple applications to process the same stream independently ✅ Offset tracking is critical because consumers should resume from where they stopped ✅ Consumer lag is one of the most important signals in stream processing systems I also implemented a small Partitioned Log with Consumer Offsets sample in Python and Java to make the concept more practical. 🛠️ ➡️ Git: https://lnkd.in/dPKzP2B5 That helped me understand a simple but important idea: 📌 Streams are not just queues 📌 Replay is a feature, not a bug 📌 Offset tracking is what makes recovery possible This is one of those topics that becomes much clearer when you build even a small version of it. Producing events is simple, but handling partitions, offsets, replay, and lag is where the real system design thinking starts. System Design is slowly becoming less about moving data from one place to another and more about building data flows that are scalable, replayable, and reliable under load. On to Day 12 📈 #SystemDesign #DistributedSystems #BackendEngineering #SoftwareEngineering #ScalableSystems #Streams #EventStreaming #PartitionedLogs #ConsumerGroups #OffsetTracking #Kafka #ApacheKafka #EventDrivenArchitecture #MessageQueues #AsyncProcessing #DataStreaming #StreamProcessing #Backpressure #ConsumerLag #Microservices #SystemArchitecture #BackendDevelopment #CloudComputing #Java #Python
To view or add a comment, sign in
-
🚀 Solved: Find Dominant Index (LeetCode) Just solved an interesting problem where the goal is to find whether the largest element in the array is at least twice as large as every other number. 💡 Approach: 1. First, traverse the array to find the maximum element and its index. 2. Then, iterate again to check if the max element is at least twice every other element. 3. If the condition fails for any element → return "-1". 4. Otherwise → return the index of the max element. 🧠 Key Insight: Instead of comparing all pairs, just track the maximum and validate it — keeps the solution clean and efficient. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Code (Java): class Solution { public int dominantIndex(int[] nums) { int max = -1; int index = -1; // Step 1: find max and index for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; index = i; } } // Step 2: check condition for (int i = 0; i < nums.length; i++) { if (i == index) continue; if (max < 2 * nums[i]) { return -1; } } return index; } } 🔥 Got 100% runtime and 99%+ memory efficiency! #LeetCode #DSA #Java #Coding #ProblemSolving #Algorithms
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