🧩 Day 29 — 3Sum Closest (LeetCode 16) 📝 Problem Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 🔁 Approach -Sort the array to use the two-pointer technique effectively. -Iterate through each element nums[i] (except the last two) and treat it as the first element of the triplet. -For each i, set two pointers: -left = i + 1 -right = len(nums) - 1 -Compute the sum of the three numbers: -total = nums[i] + nums[left] + nums[right] -If total == target, return total immediately (perfect match). -Otherwise, compare the absolute difference between total and target to update the closestSum. -Adjust pointers: -If total < target, move left pointer right to increase sum. -If total > target, move right pointer left to decrease sum. -Continue until all triplets are checked. -Return the final closestSum. 📊 Complexity -Time Complexity: O(n²) -Space Complexity: O(1) 🔑 Concepts Practiced -Sorting and two-pointer pattern -Optimization using sorted array and pointer movement -Handling duplicates efficiently -Absolute difference comparison for closest value #Leetcode #python #DSA #Sorting #problemSolving
Solving 3Sum Closest Problem on LeetCode with Python
More Relevant Posts
-
🧩 Day 30 — 4Sum (LeetCode 18) 📝 Problem -Given an integer array nums, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: -a, b, c, and d are distinct indices -nums[a] + nums[b] + nums[c] + nums[d] == target -Return the answer in any order. 🔁 Approach -Sort the array to handle duplicates efficiently. -Use a recursive k-sum approach that generalizes 2-sum, 3-sum, and 4-sum problems. -For k > 2, recursively reduce the problem: -Fix one number and call kSum for k - 1 on the remaining array. -Skip duplicates to avoid repeating quadruplets. -For k = 2, use the two-pointer technique: -Move pointers inward based on the sum comparison with the target. -Add valid pairs to the result and skip duplicates. -Backtrack after each recursive call to explore all possible combinations. 📊 Complexity -Time Complexity : O(n³) -Space Complexity : O(k) 🔑 Concepts Practiced -Recursive K-Sum pattern -Two-pointer technique -Sorting and duplicate handling -Backtracking with controlled search space #python #DSA #4Sum #ProblemSolving #Leetcode
To view or add a comment, sign in
-
-
Day 72: Partition List 🔗 I'm back to linked lists on Day 72 of #100DaysOfCode by solving "Partition List." The challenge is to rearrange a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x, while preserving the original relative order within each partition. My solution uses a two-list approach with dummy nodes: Creation of Two Lists: I initialize two separate dummy nodes: less_dummy and greater_dummy. Partitioning: I iterate through the original list once. If a node's value is less than x, I append it to the less list; otherwise, I append it to the greater list. This inherently preserves the relative order within each group. Merging: After the single pass, I set the next pointer of the tail of the less list to the head of the greater list (less_tail.next = greater_dummy.next). Crucially, I set the tail of the greater list to None to prevent cycles (greater_tail.next = None). This single-pass method achieves an optimal O(n) time complexity and O(1) extra space complexity (excluding the new nodes being rearranged). My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #LinkedList #100DaysOfCode #ProblemSolving
To view or add a comment, sign in
-
-
✅ Day 96 Completed – Inorder Traversal Today’s challenge was all about performing Inorder Traversal on a binary tree — a fundamental operation in tree data structures. 🧩 Concept: Inorder traversal visits nodes in the Left → Root → Right order. The task was to implement it without using recursion or an explicit stack, making it an interesting optimization problem. 💡 Approach: The solution uses the Morris Traversal algorithm, which cleverly utilizes threaded binary trees to achieve traversal in O(1) space complexity. It creates temporary links (threads) to predecessor nodes. Once a node’s left subtree is visited, the link is removed, ensuring no extra memory usage. ⚙️ Key Highlights: Space-efficient (no recursion/stack) Time complexity: O(N) All test cases passed ✅ (1111/1111 with 100% accuracy) 🌱 Takeaway: This problem deepened my understanding of space-optimized tree traversal techniques and their practical applications. #100DaysOfCode #Day96 #GeeksforGeeks #Python #DataStructures #BinaryTree #InorderTraversal
To view or add a comment, sign in
-
-
🚀 Day 40 / 100 — #100DaysOfLeetCode 💡 (1625) Lexicographically Smallest String After Applying Operations (Medium) This was a really fun graph + BFS problem disguised as a string manipulation challenge. The trick is realizing that applying the two operations (add & rotate) repeatedly explores a finite set of states, forming an implicit graph, where each node is a string transformation. 🧩 Problem Overview You are given: A numeric string s Two integers a and b You can repeatedly: Add a (mod 10) to all digits at odd indices. Rotate the string right by b positions. Find the lexicographically smallest string possible after any number of operations. ⚙️ Approach — BFS on States Used Breadth-First Search (BFS) to explore all reachable strings: Start from the initial string s. Use a set vis to track visited states. For each string, generate: One by performing addition on odd indices. One by rotating by b. Continue until all unique transformations are explored. Track the smallest lexicographical string seen. 📈 Complexities Time Complexity: O(10 * n) Each state can appear up to 10 times due to modulo operations, and each state has n length. Space Complexity: O(10 * n) For storing visited transformations. ✅ Key Insights The problem is finite because both operations are modular and cyclic. BFS guarantees we explore all possible reachable strings in an optimal manner. Lexicographical comparison after BFS is straightforward — track the smallest string so far. ✨ Takeaway This problem beautifully demonstrates how: “Even string problems can secretly be graph traversal problems.” It’s a neat mix of modular arithmetic, rotation logic, and state-space search. #LeetCode #100DaysOfCode #BFS #GraphTraversal #StringManipulation #ProblemSolving #Python #Algorithms
To view or add a comment, sign in
-
-
DAY-1:CODING CHALLENGE 1.Longest common Prefix substring from given string as input 2.3SUM problem Started with BRUTE-FORCE → checked every triplet. 😀 Worked 😇 but SLOW for big arrays (O(n³)) → TIME LIMIT EXCEEDED. Faced errors along the way: 'int object not iterable' → I wrote sorted(a,b,c) instead of sorted([a,b,c]). 'unhashable type: list' → Tried adding list to set. Fixed by converting to tuple. LOGICAL BUG → Return inside the loop returned early. Fixed by moving return outside. Finally moved to OPTIMAL TWO-POINTER APPROACH: Sort array first. Use two pointers to find pairs for target -nums[i]. Skip duplicates carefully. Complexity reduced to O(n²). 💡 Lessons learned: small syntax mistakes can cause big errors, immutable types are key for sets, and proper pointer logic makes code efficient. #Python #Algorithms #LeetCode #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 57: Binary Tree Zigzag Level Order Traversal 🎢 I'm continuing my journey with an advanced tree traversal problem on Day 57 of #100DaysOfCode: "Binary Tree Zigzag Level Order Traversal." The challenge is to return the nodes of a binary tree level by level, alternating the direction of traversal (left-to-right, then right-to-left, and so on). My solution builds upon the standard Breadth-First Search (BFS) algorithm, using a queue (deque): Level Traversal: I process the tree level by level, finding the level_size in each iteration. Direction Toggle: I use a boolean flag (left_to_right) to track the current direction. Zigzag Logic: Inside the level loop, I use a simple conditional: if left_to_right is true, I append the node value normally. If it's false, I insert the node value at the beginning of the current level's list (current_level.insert(0, node.val)). Optimal Flip: After processing the entire level, I flip the left_to_right flag (left_to_right = not left_to_right) for the next level. This single-pass BFS approach ensures all nodes are visited exactly once, achieving an optimal O(n) time complexity and O(n) space complexity. My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #Trees #BFS #100DaysOfCode #ProblemSolving #Zigzag
To view or add a comment, sign in
-
-
🚀 𝐃𝐚𝐲 𝟏𝟑 𝐨𝐟 #𝟏𝟔𝟎𝐃𝐚𝐲𝐬𝐎𝐟𝐂𝐨𝐝𝐞 — 𝐏𝐚𝐥𝐢𝐧𝐝𝐫𝐨𝐦𝐞 𝐍𝐮𝐦𝐛𝐞𝐫 | 𝐒𝐭𝐫𝐢𝐧𝐠𝐬 🧩 Today’s focus was on a simple yet classic logic check — determining if a number reads the same forward and backward. While it looks straightforward, it’s a great reminder that elegant solutions often come from clarity, not complexity. Problem: 𝐂𝐡𝐞𝐜𝐤 𝐢𝐟 𝐚𝐧 𝐢𝐧𝐭𝐞𝐠𝐞𝐫 𝐢𝐬 𝐚 𝐩𝐚𝐥𝐢𝐧𝐝𝐫𝐨𝐦𝐞. Approach: Convert the integer to a string and compare it with its reverse. Time Complexity: O(n) Space Complexity: O(n) This small exercise reinforces foundational reasoning that scales up when designing more complex systems — where reversing, mirroring, or symmetry detection shows up in data validation, pattern recognition, and even natural language tasks. 🔗 GitHub: https://lnkd.in/gaim_PJS #Python #LeetCode #CodingChallenge #160DaysOfCode #ProblemSolving #DSA #AIEngineerJourney
To view or add a comment, sign in
-
🚀 DSA Progress – Day 112 ✅ Problem #560: Subarray Sum Equals K 🧠 Difficulty: Medium | Topics: Array, Prefix Sum, Hash Map 🔍 Approach: Implemented the Prefix Sum + Hash Map technique to efficiently count subarrays whose sum equals k. Step 1 (Prefix Sum): Maintain a running sum (prefix_sum) as we iterate through the array. Step 2 (Check for Required Sum): For each prefix_sum, check if (prefix_sum - k) exists in the hashmap. If yes → it means a subarray ending at the current index sums to k. Step 3 (Store Frequency): Use a dictionary (mp) to store how many times each prefix sum has appeared. This allows counting multiple subarrays efficiently. 🕒 Time Complexity: O(n) 💾 Space Complexity: O(n) (for hashmap storage) 📁 File: https://lnkd.in/g7acMKiA 📚 Repo: https://lnkd.in/g8Cn-EwH 💡 Learned: This problem strengthened my understanding of how prefix sums can simplify subarray-related questions. Instead of manually checking every subarray, we convert the problem into recognizing a pattern using previous sums. This is a powerful technique that shows up frequently in interview-level array problems. ✅ Day 112 complete — counted hidden subarrays like a pro! 🔢🎯✨ #LeetCode #DSA #Python #Arrays #PrefixSum #HashMap #Algorithm #DailyCoding #InterviewPrep #GitHubJourney #ProblemSolving
To view or add a comment, sign in
-
Day 16 of #100DaysOfLeetCode Today’s problem focused on substring counting within binary strings and required an efficient approach to handle potentially large input sizes without generating every substring explicitly. 1. Number of Substrings With Only 1s The task was to count the total number of substrings that consist entirely of the character '1', with the final result taken modulo (10^9 + 7). Instead of constructing the substrings, the key insight is that each continuous block of 1s contributes a predictable number of valid substrings. 🔹 My Approach: Iterated through the string while tracking the current streak length of consecutive 1s. Each time a block ended, computed the number of substrings from that block using the formula: k*(k+1)/2 where k is the length of the streak. Added the total from each block to the final answer, applying the modulo constraint throughout. Completed the process with a final update for any trailing block of 1s. What I Learned: This problem reinforces how recognizing mathematical patterns within sequences can transform a brute-force solution into a simple linear scan. Efficient substring counting often comes down to understanding structure rather than enumerating possibilities. 📊 Complexity Analysis: Time Complexity: O(n) — single pass over the string. Space Complexity: O(1) — constant space approach. #day16 #100daysofleetcode #leetcode #DSA #python #leetcodes #striver
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 98 Problem: Count and Say 🔢🗣️ This problem is a fun example of string construction and pattern recognition, where each term of the sequence describes the previous one — a great exercise in iterative logic and encoding patterns. 🧠 Problem Summary: The Count and Say sequence is defined recursively: countAndSay(1) = "1" countAndSay(n) is the run-length encoding of countAndSay(n - 1) For example: 1 11 → one 1 21 → two 1s 1211 → one 2, one 1 111221 → one 1, one 2, two 1s ⚙️ My Approach: 1️⃣ Base cases: return "1" for n=1, "11" for n=2. 2️⃣ Start with "11" and iteratively build the next term by counting consecutive identical digits. 3️⃣ Construct each new term using run-length encoding logic. 4️⃣ Repeat this process until reaching the nth term. 📈 Complexity Analysis: Time: O(n × m) → where m is the average length of intermediate strings. Space: O(m) → for storing the temporary encoded string. ✨ Key Takeaway: This challenge reinforces how string processing and pattern generation can be elegantly solved through careful iteration — a perfect blend of logic and observation. 🔖 #DSA #100DaysOfCode #LeetCode #ProblemSolving #StringManipulation #Python #Algorithms #CodingChallenge #TechCommunity #InterviewPrep #LearningEveryday #CountAndSay
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