Day 1 — 100 Days of Code | Solved Two Sum Problem (LeetCode) Today I solved the classic Two Sum problem, one of the most common problems asked in coding interviews. 🧩 Problem https://lnkd.in/g9KcCNRv Given an array of integers nums and an integer target, return the indices of two numbers such that their sum equals the target. Example: nums = [2,7,11,15] target = 9 Output → [0,1] Because: nums[0] + nums[1] = 2 + 7 = 9 💡 My Approach At first, the straightforward idea was: Brute Force Approach Check every pair using two loops Time Complexity → O(n²) But we can optimize it. Optimized Approach (HashMap) Idea: Iterate through the array once For each element calculate the complement complement = target - current number Check if complement already exists in HashMap If yes → solution found Otherwise store current number and index in map This reduces time complexity significantly. 🧠 Complexity Time Complexity → O(n) Space Complexity → O(n) 💻 Java Solution import java.util.HashMap; 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[]{-1,-1}; } } 📚 Key Learning This problem helped me understand the HashMap + Complement pattern, which is useful in many problems like: Pair Sum Subarray Sum Two Sum variants Excited to continue my #100DaysOfCode journey 🚀 Hashtags #100DaysOfCode #Java #DSA #LeetCode #ProblemSolving #CodingJourney #SoftwareEngineering #BackendDeveloper
Two Sum Problem Solved with HashMap and Complement Approach
More Relevant Posts
-
💻 LeetCode Daily Challenge – Find Unique Binary String (Problem 1980) Today's LeetCode Daily Challenge was "Find Unique Binary String". 📌 Problem Summary We are given n unique binary strings of length n. The task is to construct a binary string of length n that does not exist in the given list. 🔎 Approach 1: HashSet + Generate All Possibilities Idea: Store all given strings in a HashSet. Generate binary numbers from 0 to 2^n - 1. Convert each number to a binary string of length n. Return the first string not present in the set. Time Complexity: O(2^n) Space Complexity: O(n) 🔎 Approach 2: Backtracking Idea: Recursively generate all binary strings of length n. Check if the generated string exists in the set. Return the first missing string. Time Complexity: O(2^n) Space Complexity: O(N) 🚀 Approach 3 (Optimal – Cantor’s Diagonalization) This elegant approach guarantees a unique string. Idea: Look at the i-th character of the i-th string. Flip the bit (0 → 1 or 1 → 0). Build a new string using these flipped bits. This ensures the constructed string differs from every string at least at one position. Time Complexity: O(n) Space Complexity: O(n) 💡 Java Implementation (Optimal Approach) class Solution { public String findDifferentBinaryString(String[] nums) { StringBuilder res = new StringBuilder(); for(int i = 0; i < nums.length; i++){ char ch = nums[i].charAt(i); if(ch == '0') res.append('1'); else res.append('0'); } return res.toString(); } } 📚 Key Takeaway This problem demonstrates a clever application of Cantor’s Diagonalization, allowing us to construct a guaranteed unique binary string in linear time. #LeetCodeDaily #DSA #Java #ProblemSolving #CodingPractice #SoftwareEngineering
To view or add a comment, sign in
-
🚀#Day21 Of #75DaysOfLeetCode 🚀 Three Weeks of Leetcode LeetCode Problem Solved: Unique Number of Occurrences (1207) Today I solved an interesting HashMap + HashSet problem that focuses on counting frequencies and checking uniqueness. 🔹 Problem: Given an integer array arr, return true if the number of occurrences of each value in the array is unique, otherwise return false. 🔹 Example: Input: [1,2,2,1,1,3] Frequency of elements: 1 → 3 times 2 → 2 times 3 → 1 time Since all frequencies are different, the output is true. 💡 Approach: 1️⃣ Use a HashMap to count the frequency of each element. 2️⃣ Store the frequencies in a HashSet. 3️⃣ If the size of the HashSet equals the size of the HashMap, all occurrences are unique. 💻 Java Solution: import java.util.*; class Solution { public boolean uniqueOccurrences(int[] arr) { HashMap<Integer, Integer> map = new HashMap<>(); for(int num : arr){ map.put(num, map.getOrDefault(num, 0) + 1); } HashSet<Integer> set = new HashSet<>(map.values()); return map.size() == set.size(); } } 📊 Complexity: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) Problems like this strengthen understanding of hashing, frequency counting, and set operations, which are very common in coding interviews. #LeetCode #DSA #Java #CodingPractice #HashMap #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Day 22 of #75DaysofLeetCode LeetCode Problem Solved: Determine if Two Strings Are Close (1657) Another interesting String + Frequency Analysis problem from LeetCode! 🔹 Problem: Two strings are considered close if we can transform one into the other using: 1️⃣ Swap any two characters (rearranging characters). 2️⃣ Transform all occurrences of one character into another existing character and vice versa. We need to determine whether word1 can be converted into word2 using these operations. 💡 Key Insights: To make two strings close, three conditions must hold: ✔️ Both strings must have the same length. ✔️ Both strings must contain the same set of characters. ✔️ The frequency distribution of characters must match after sorting. Why? Because operation 2 allows us to swap character frequencies between existing characters. 💻 Java Solution: import java.util.*; class Solution { public boolean closeStrings(String word1, String word2) { if(word1.length() != word2.length()) return false; int[] freq1 = new int[26]; int[] freq2 = new int[26]; for(char c : word1.toCharArray()) freq1[c - 'a']++; for(char c : word2.toCharArray()) freq2[c - 'a']++; for(int i = 0; i < 26; i++){ if((freq1[i] == 0 && freq2[i] != 0) || (freq1[i] != 0 && freq2[i] == 0)) return false; } Arrays.sort(freq1); Arrays.sort(freq2); return Arrays.equals(freq1, freq2); } } 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Problems like this help strengthen understanding of hashing, frequency counting, and string manipulation, which are common in coding interviews. #LeetCode #DSA #Java #CodingPractice #Algorithms #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 17 of #75DaysofLeetCode LeetCode Problem Solved: Longest Subarray of 1's After Deleting One Element (Sliding Window) Today I solved LeetCode 1493 – Longest Subarray of 1's After Deleting One Element. This problem is a great example of applying the Sliding Window / Two Pointer technique to optimize array problems. 🔹 Problem Statement: Given a binary array nums, we must delete exactly one element and then find the longest non-empty subarray containing only 1's. 💡 Approach: The key idea is to maintain a sliding window that allows at most one 0 in the window. If the number of zeros exceeds one, we move the left pointer to shrink the window until the condition becomes valid again. Since we must delete one element, the final answer becomes: window_size - 1 ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Java Implementation: class Solution { public int longestSubarray(int[] nums) { int left = 0; int zeroCount = 0; int maxLen = 0; for (int right = 0; right < nums.length; right++) { if (nums[right] == 0) { zeroCount++; } while (zeroCount > 1) { if (nums[left] == 0) { zeroCount--; } left++; } maxLen = Math.max(maxLen, right - left + 1); } return maxLen - 1; } } 📚 Practicing problems like this helps strengthen understanding of Sliding Window patterns, which are frequently asked in coding interviews. #LeetCode #Java #DSA #SlidingWindow #ProblemSolving #CodingPractice #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 LeetCode Practice – Longest Common Prefix (Java) Continuing my DSA practice series, today I solved the Longest Common Prefix problem. 📌 Problem Statement Write a function to find the longest common prefix among an array of strings. If there is no common prefix, return an empty string "". Example: Input - ["flower","flow","flight"] Output - "fl" 💡 Optimized Approach (Sorting Trick) Key Idea: If we sort the array of strings, the strings with the most differences will move to the first and last positions. So the longest common prefix of the entire array must be the common prefix between the first and last string. Example: Original: ["flower","flow","flight"] After sorting: ["flight","flow","flower"] Now we only compare: first = "flight" last = "flower" Common prefix: f ✔ l ✔ i ✖ Result:- "fl" 💻 Java Code import java.util.Arrays; class Solution { public String longestCommonPrefix(String[] strs) { StringBuilder s = new StringBuilder(); Arrays.sort(strs); char first[] = strs[0].toCharArray(); char last[] = strs[strs.length - 1].toCharArray(); for(int i = 0; i < first.length; i++){ if(first[i] != last[i]){ break; } else { s.append(first[i]); } } return s.toString(); } } ⚡ Time Complexity - O(n log n) Because we sort the array. ⚡ Space Complexity - O(1) 📚 Key Learning Sorting the strings allows us to reduce the comparison to only two strings instead of all strings, which simplifies the logic significantly. Consistent DSA practice helps improve problem-solving ability and coding efficiency for technical interviews. #leetcode #java #datastructures #algorithms #codingpractice #softwaredevelopment
To view or add a comment, sign in
-
🚀 Day 93 of My 100 Days LeetCode Challenge | Java Today’s problem explored recursion and backtracking, focusing on generating valid strings under specific constraints. The challenge was to generate happy strings of length n, where: The string consists only of 'a', 'b', and 'c' No two adjacent characters are the same From all possible happy strings, the goal was to find the k-th lexicographical string. To solve this, I used a backtracking approach that builds the string step by step. At each step, we try adding characters while ensuring they don't match the previous character. This naturally generates all valid happy strings in lexicographical order. Once all valid strings are generated, we simply return the k-th one if it exists. ✅ Problem Solved: The k-th Lexicographical Happy String of Length n ✔️ All test cases passed (345/345) ⏱️ Runtime: 22 ms 🧠 Approach: Backtracking + Recursion 🧩 Key Learnings: ● Backtracking is ideal for generating constrained combinations. ● Pruning invalid states early improves efficiency. ● Recursion makes exploring possible paths intuitive. ● Lexicographical generation often comes naturally with ordered iteration. ● Constraint-based string generation is a common interview pattern. This problem was a great exercise in systematically exploring possibilities while enforcing constraints. 🔥 Day 93 complete — strengthening recursion and backtracking intuition. #LeetCode #100DaysOfCode #Java #Backtracking #Recursion #ProblemSolving #DSA #CodingJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Day 44 of #100DaysOfCode — Mastering HashSet Internals in Java Today I went deep into one of the most commonly used collections in Java — HashSet 🔥 Not just usage… but how it actually works internally. 🧠 What is HashSet? 👉 HashSet is backed by a HashMap 👉 Stores elements as keys with a dummy value ⚙️ How HashSet Adds an Element? add(element) ↓ hashCode() → object-specific logic ↓ hash = h ^ (h >>> 16) // bit spreading ↓ index = (n - 1) & hash // bucket index ↓ bucket check ↓ if empty → insert if collision: ↓ equals() check ↓ if duplicate → reject ❌ else: ↓ add to LinkedList ↓ if bucket size ≥ 8 and capacity ≥ 64 → convert to Tree ↓ if bucket size ≤ 6 → convert back to LinkedList 🔍 Key Concepts I Learned 🔹 1. hashCode() Converts object → integer Used to decide bucket location 🔹 2. equals() Used to check duplicate Same hashCode ≠ same object 🔹 3. Collision Handling Multiple elements in same bucket Stored as: LinkedList (< 8 elements) Red-Black Tree (≥ 8 elements) 🌳 Tree Conversion Rules Bucket size ≥ 8 → Tree Bucket size ≤ 6 → Back to LinkedList Capacity must be ≥ 64 for tree conversion 🔄 Rehashing (Very Important) Default capacity = 16 Load factor = 0.75 👉 Threshold = 16 × 0.75 = 12 When size exceeds 12: Capacity doubles → 32 All elements are rehashed New bucket positions are recalculated ⚡ Why HashSet is Fast? Average Time Complexity: O(1) Due to: Efficient hashing Bitwise index calculation Tree optimization for collisions 🧠 Final Takeaway 👉 hashCode decides bucket 👉 equals decides duplicate 👉 structure (List/Tree) depends on size This deep dive really helped me understand why overriding hashCode() and equals() is critical in real-world applications. 🙏 Special thanks to my mentor Suresh Bishnoi sir for guiding me through these concepts and helping me understand the internals so clearly! #Java #HashSet #DataStructures #BackendDevelopment #CodingJourney #100DaysOfCode #LearnInPublic
To view or add a comment, sign in
-
-
𝐂𝐚𝐧 𝐰𝐞 𝐨𝐯𝐞𝐫𝐫𝐢𝐝𝐞 𝐭𝐡𝐞 "𝐦𝐚𝐢𝐧()" 𝐦𝐞𝐭𝐡𝐨𝐝 𝐢𝐧 𝐉𝐚𝐯𝐚? In my previous post, we discussed that the "main()" method is static. No — we cannot override the "main()" method Why ? Because "main()" is static. And we cannot override static methods And in Java: 📃Overriding happens at runtime ⏱️ 📃 It depends on objects 👤 But ❌ Static methods belong to the class ❌ They are loaded during class loading time (before objects are created) 🔍𝐖𝐡𝐚𝐭 𝐚𝐜𝐭𝐮𝐚𝐥𝐥𝐲 𝐡𝐚𝐩𝐩𝐞𝐧𝐬 𝐭𝐡𝐞𝐧? You can write a main() method in a child class ❌ But it does not override the parent’s main(). It’s called "𝐌𝐞𝐭𝐡𝐨𝐝 𝐇𝐢𝐝𝐢𝐧𝐠". 𝐜𝐥𝐚𝐬𝐬 𝐏𝐚𝐫𝐞𝐧𝐭 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐏𝐚𝐫𝐞𝐧𝐭 𝐦𝐚𝐢𝐧"); } } 𝐜𝐥𝐚𝐬𝐬 𝐂𝐡𝐢𝐥𝐝 𝐞𝐱𝐭𝐞𝐧𝐝𝐬 𝐏𝐚𝐫𝐞𝐧𝐭 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐂𝐡𝐢𝐥𝐝 𝐦𝐚𝐢𝐧"); } } 𝐩𝐮𝐛𝐥𝐢𝐜 𝐜𝐥𝐚𝐬𝐬 𝐃𝐞𝐦𝐨 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐏𝐚𝐫𝐞𝐧𝐭 𝐩 = 𝐧𝐞𝐰 𝐂𝐡𝐢𝐥𝐝(); 𝐩.𝐦𝐚𝐢𝐧(𝐚𝐫𝐠𝐬); // 𝐜𝐚𝐥𝐥𝐬 𝐏𝐚𝐫𝐞𝐧𝐭 𝐦𝐚𝐢𝐧 𝐂𝐡𝐢𝐥𝐝.𝐦𝐚𝐢𝐧(𝐚𝐫𝐠𝐬); // 𝐜𝐚𝐥𝐥𝐬 𝐂𝐡𝐢𝐥𝐝 𝐦𝐚𝐢𝐧 } } Output : Parent main Child main ♟️These main() methods are not called automatically by the JVM — they run only when we explicitly invoke them. ♟️Only main(String[] args) is invoked automatically by JVM. Other overloaded or hidden main() methods are executed only when explicitly called. 🚀 𝐅𝐢𝐧𝐚𝐥 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 "main()" method cannot be overridden because it is static — it can only be hidden #Java #JavaDeveloper #JavaBackend #Programming #TechJourney #LearnBySharing #JavaConcepts #OOP #InterviewPrep
To view or add a comment, sign in
-
🚀 Day 11 of #50DaysLeetCode Challenge Today I tackled a HARD problem: “Regular Expression Matching” on LeetCode using Java. 🔹 Problem: Given a string "s" and a pattern "p", implement regex matching with support for: • "." → matches any single character • "*" → matches zero or more of the preceding element Return true if the entire string matches the pattern. Example: Input: "s = "aa", p = "a*"" → Output: "true" Input: "s = "aa", p = "a"" → Output: "false" 🔹 Approach I Used: I used Dynamic Programming (DP) — anything else here is inefficient or breaks on edge cases. ✔ Created a 2D DP table "dp[m+1][n+1]" ✔ "dp[i][j]" represents whether "s[0...i-1]" matches "p[0...j-1]" ✔ Handled "*" carefully: - Treat it as zero occurrence → "dp[i][j-2]" - Or one/more occurrence → match previous character ✔ Built the solution bottom-up 🔹 Concepts Practiced: • Dynamic Programming (2D DP) • String pattern matching • Handling complex edge cases #LeetCode #DSA #Java #DynamicProgramming #Algorithms #CodingChallenge #50DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 26 of 30 Days of Java: Let's Map It Out! Today, we're diving deep into one of the most essential data structures in Java: the Map interface! Think of it like a super-powered dictionary. A Map stores data as key-value pairs, where each unique key points to a specific value. It's the go-to structure whenever you need efficient data retrieval based on a unique identifier. Java gives us several powerful Map implementations, each with its own special features. We explored the most common ones: 🚀 HashMap: The fastest option, but doesn't guarantee any specific order of elements. Great for maximum performance! 🔗 LinkedHashMap: Maintains the order of elements based on insertion. Useful when order matters! 🌳 TreeMap: Stores keys in their natural sorted order (e.g., alphabetical or numerical). Perfect for sorted data retrieval! 🔒 Hashtable: A thread-safe Map, but slower than HashMap. Used mainly in multithreaded environments! We also looked at some essential Map methods: put(key, value): Adds a new key-value pair to the Map. get(key): Retrieves the value associated with a given key. remove(key): Deletes the key-value pair for a specific key. containsKey(key): Checks if a particular key exists in the Map. containsValue(value): Checks if a certain value exists in the Map. size(): Returns the number of key-value pairs in the Map. clear(): Removes all key-value pairs from the Map. And we learned a couple of ways to iterate through a Map, so we can access and process each element. The choice of which Map implementation to use depends on your specific needs: performance, order, sorted keys, or thread safety. Maps are absolutely fundamental in Java programming, from handling user data to building complex applications. Check out the sketchnote for a quick visual summary of these Map types and their characteristics! #Java #Programming #DataStructures #MapInterface #JavaHashMap #LinkedHashMap #JavaTreeMap #JavaHashtable #LearningJava #Coding #SoftwareEngineering #DeveloperLife #TechLearning #30DaysOfJava
To view or add a comment, sign in
-
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