🚀 Day 54 Out of #365DaysOfCode -LeetCode Maximum Product of Word Lengths (Optimized with Bit Manipulation) Github link: https://lnkd.in/gGUy_MKZ Today I worked on an interesting string problem that initially caused a Time Limit Exceeded (TLE) error using a brute-force character comparison approach. 🔎 Problem Statement: Given an array of words, find the maximum value of length(word[i]) × length(word[j]) such that the two words do not share any common letters. 💡 Initial Approach: Compared every pair of words Checked characters one by one using string search Result: ❌ TLE for large inputs ⚡ Optimized Approach (Bit Masking): Represented each word as a 26-bit integer (for letters a–z) Used bitwise AND to check if two words share common letters If (mask[i] & mask[j]) == 0, the words are valid Reduced repeated character comparisons significantly 📈 Key Learnings: Bit manipulation can drastically improve string comparison problems Preprocessing data smartly reduces redundant computation Always look for patterns when constraints are small (like 26 lowercase letters) This problem reinforced how optimization techniques can turn an inefficient O(n² × wordLength) approach into a much faster solution. #Java #DSA #BitManipulation #ProblemSolving #LeetCode #CodingJourney
Max Product of Word Lengths without Common Letters
More Relevant Posts
-
DSA series... 🚀 Chapter 2: "Sliding Window Fixed Size" LeetCode#30: (Level: Hard) Substring with Concatenation of All Words... This problem can be solved efficiently using the "Sliding Window + HashMap" approach to detect valid word combinations inside a string. Simple Flow Explanation... ✍️ 1⃣ Initialize Essentials... - Check edge cases and calculate the "single word length" and the "total length of all words combined". 2⃣ Map the Target Words... - Store each word and its expected frequency in a "HashMap" to know how many times it should appear. 3⃣ Use Offset Strategy... - Since every word has the same length, start sliding windows from multiple offsets (0 to wordLength−1) to cover all possible positions. ** Expand the Window ** - Move the "right pointer" word by word and add each discovered word to the current frequency map. ** Shrink the Window ** - If a word appears more times than expected, move the "left pointer" to remove extra words from the window. 4⃣ Match and Record... - When the window contains all required words with correct frequencies, record the starting index. 5⃣ Reset on Invalid Word... - If a word is "not in the target list", clear the current window and start checking from the next position. Why This Works... 🛠️ Instead of checking every substring, we treat the string as fixed-length word blocks and slide the window efficiently. Complexity... 📊 Time Complexity : O(n × wordLength). Space Complexity : O(m) ; m -> Unique words. Stay tuned for next chapter that was "Sliding Window - Dynamic Programming"... 🔥 If you have any thoughts and suggestions, Drop on the comment section or DM me... 💬 #Java #Algorithms #SlidingWindow #LeetCode #CodingInterview #DSA #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 72 - LeetCode Journey Solved LeetCode 206: Reverse Linked List (Easy) today — one of the most fundamental problems for understanding linked list manipulation and pointer handling. The task is to reverse a singly linked list so that the direction of all pointers is flipped. 💡 Core Idea: Traverse the list once and reverse the pointer of each node. We maintain three pointers: • prev → previous node (initially null) • curr → current node being processed • next → stores the next node before changing links At each step: Save the next node Reverse the current node’s pointer Move both pointers forward This continues until we reach the end of the list. ⚡ Key Learning Points: • Understanding pointer manipulation in linked lists • Reversing links without extra space • Maintaining O(n) time complexity and O(1) space • Building a foundation for many advanced linked list problems This is a must-know pattern because it appears frequently in variations like: Reverse Linked List II Reverse Nodes in k-Group Palindrome Linked List ✅ Stronger understanding of linked list pointers ✅ Improved confidence with pointer manipulation ✅ Solid foundation for advanced linked list questions Small problems like this build the fundamentals of strong data structure skills 🚀 #LeetCode #DSA #Java #LinkedList #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
I didn't expect a linked list concept in an array problem. But that's exactly what this was. 🚀 Day 59/365 — DSA Challenge Solved: Find the Duplicate Number The problem: Given n + 1 numbers Each number is in range [1, n] There is exactly one duplicate. Find it. Constraint: ❌ Can't modify array ❌ O(1) extra space only At first, this looks like an array problem. But the trick is... 👉 Treat it like a linked list 💡 Key idea: Each value points to an index nums[i] → next index This creates a cycle. And the duplicate number is the entry point of the cycle So I used: 👉 Floyd's Cycle Detection Algorithm (slow & fast pointers) Step 1: Move slow by 1 Move fast by 2 They will meet inside the cycle Step 2: Reset slow to start Move both by 1 Where they meet again = duplicate ⏱ O(n) time 📦 O(1) space This problem taught me: Sometimes the solution is not in the data structure you see... But in how you interpret it. Code 👇 https://lnkd.in/dad5sZfu #DSA #LearningInPublic #Java #LeetCode #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
Day 4/100 – LeetCode Challenge Problem: Valid Anagram Today’s problem focused on string comparison using frequency counting instead of sorting. Problem Statement: Given two strings s and t, determine if t is an anagram of s. An anagram means: Same characters Same frequency Order does NOT matter Approach (Optimized – O(n)): If lengths are different → return false Create an integer array of size 26 (for lowercase letters) Increment count for characters in s Decrement count for characters in t If all values are zero → valid anagram This ensures: Time Complexity: O(n) Space Complexity: O(1) (fixed array of size 26) Key Concepts Practiced: Hashing technique Character indexing using ASCII (char - 'a') Optimizing from sorting to counting Constant space optimization #100DaysOfCode #LeetCode #DSA #Java #CodingInterview #SoftwareEngineerJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 DSA Journey | Day 4 — Majority Element (LeetCode) Today, I solved the Majority Element problem and focused on improving my approach from a brute force solution to an optimized one. 🔹 🧠 Problem Understanding Given an integer array, the task is to find the element that appears more than ⌊n/2⌋ times. ✔ The problem guarantees that a majority element always exists ✔ Focus is on optimizing the approach efficiently 🔹 ⚙️ Approach 1: Brute Force For each element, I traversed the entire array again to count its frequency If the frequency exceeded n/2, I returned that element ❌ Time Complexity: O(n²) 👉 Works fine but not scalable for large inputs 🔹 ⚡ Approach 2: Optimized (Using HashMap) Stored frequency of elements using a HashMap Identified the element with count greater than n/2 ✔ Time Complexity: O(n) ✔ Space Complexity: O(n) 💡 Significant improvement compared to brute force 🔹 💡 Key Learnings ✔ How to optimize from O(n²) → O(n) ✔ Importance of choosing the right data structure ✔ Better understanding of frequency-based problems #DSA #LeetCode #Java #ProblemSolving #CodingJourney #Day4 #Learning #Algorithms
To view or add a comment, sign in
-
-
🔥 Day 92 of #100DaysOfCode Today’s challenge: LeetCode – Search a 2D Matrix 🧩📊 📌 Problem Summary You are given a matrix where: Each row is sorted in ascending order The first element of each row is greater than the last element of the previous row 👉 This means the entire matrix behaves like a sorted 1D array. Goal: Return true if target exists, otherwise false. 🧠 Approach: Double Binary Search Instead of scanning row by row, we use Binary Search twice. Step 1️⃣: Find the Correct Row Binary search on rows: If target > last element of row → move down If target < first element of row → move up Otherwise → target must be inside this row Step 2️⃣: Binary Search Inside That Row 💡 Why This Works? Because: Rows are sorted Row ranges don’t overlap It behaves like a flattened sorted array. ⏱ Time Complexity: O(log m + log n) 💾 Space Complexity: O(1) 🚀 Performance Runtime: 0 ms Beats 100% submissions Memory: Very efficient 🔥 🧠 Key Learning Whenever: Data looks 2D But ordering behaves like 1D 👉 Think Binary Search Optimization Stack → Sliding Window → Queue → Binary Search → Matrix Search Patterns are connecting now 💪 On to Day 93 🚀 #100DaysOfCode #LeetCode #BinarySearch #Matrix #Java #DSA #InterviewPrep
To view or add a comment, sign in
-
-
Day 18/100 – LeetCode Challenge Problem Solved: Reverse Linked List Today’s problem focused on reversing a singly linked list. While it looks simple, it’s a fundamental concept that tests pointer manipulation and understanding of linked structures. The idea is to iterate through the list and reverse the direction of each node’s pointer. At every step, we keep track of three things: the current node, the previous node, and the next node. We reverse the link by pointing the current node to the previous one, then move all pointers one step forward. By the end of the traversal, the previous pointer will be pointing to the new head of the reversed list. Time Complexity: O(n) Space Complexity: O(1) Performance: Runtime 0 ms Key takeaway: Linked list problems are all about pointer control. Mastering how pointers move and change direction is essential for solving more complex problems efficiently. Day 18 completed. Staying consistent and reinforcing core data structure fundamentals. #100DaysOfLeetCode #Java #LinkedList #Algorithms #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
#100DaysOfCode 🚀 👉Solved: LeetCode 75 – Sort Colors The goal was to sort an array containing only three values: 0 (Red), 1 (White), and 2 (Blue) At first glance this looks like a simple sorting problem. But the twist: ❌ No built-in sort ✔ One pass ✔ Constant space The solution uses the famous **Dutch National Flag Algorithm**. Instead of sorting normally, we maintain three pointers: • low → for 0s • mid → current element • high → for 2s Rules: • If nums[mid] == 0 → swap with low • If nums[mid] == 1 → move mid forward • If nums[mid] == 2 → swap with high This allows sorting the array in a single pass. 📌 Key Points: ✔ In-place sorting ✔ One pass algorithm ✔ Constant space usage ✔ Classic three-pointer technique ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Problems like this show how powerful pointer techniques can be. Day 15✅ #DSA #Java #LeetCode #Algorithms #ProblemSolving #100DaysOfCode #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
🔥 Day 82 of my LeetCode Journey 🔥 📘 Problem: 110. Balanced Binary Tree 🎯 Difficulty: Easy 🔹 Problem Statement: Given a binary tree, determine if it is height-balanced. A binary tree is balanced if the height difference between the left and right subtree of every node is not more than 1. 🔹 Approach Used: Traverse the tree using Depth First Search (DFS) Calculate the height of left and right subtrees recursively If the height difference exceeds 1, return -1 to indicate the tree is not balanced Otherwise, return the height of the current node Finally, check if the returned value is -1 or not 🔹 Key Concepts: Binary Tree traversal Depth First Search (DFS) Recursion Height calculation of tree 🔹 Learning: Instead of calculating heights separately for every node (which would increase complexity), this approach combines height calculation and balance checking in a single traversal, making the solution more efficient. Time Complexity: O(n) Space Complexity: O(h) (recursion stack) #LeetCode #Day82 #Java #BinaryTree #DFS #Recursion #DSA #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 27 of #75DaysofLeetCode Solved LeetCode 933 — Number of Recent Calls Today I worked on a simple yet powerful problem that teaches an important concept used in real-world systems: sliding window over streaming data. 💡 Problem Insight: We need to count how many requests happened in the last 3000 milliseconds for every new request. 📌 Instead of checking all past requests every time (which is inefficient), we use a Queue to maintain only relevant data. ⚡ Approach: Store incoming timestamps in a queue Remove all outdated timestamps (< t - 3000) The remaining size of the queue gives the answer 🧠 This is a perfect example of: Sliding Window Technique Real-time Data Processing Efficient Queue Usage 💻 Java Code: class RecentCounter { Queue<Integer> queue = new LinkedList<>(); public int ping(int t) { queue.offer(t); while (queue.peek() < t - 3000) { queue.poll(); } return queue.size(); } } 📊 Complexity: Time: O(1) amortized Space: O(N) 🔥 Real-world connection: This concept is widely used in: API rate limiting Server request monitoring Streaming analytics ✅ Small problems like this build strong intuition for handling large-scale systems. #LeetCode #DataStructures #Java #Coding #100DaysOfCode #SoftwareEngineering #ProblemSolving
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