✨ Today marks Day 7 of my LeetCode streak! I solved a fun and logical problem that reminded me how important simple ideas like arrays and booleans can be in solving tricky questions. 💡 Problem: Find the Two Sneaky Numbers In the town of Digitville, there’s a list called nums that should contain all integers from 0 to n - 1 exactly once. But two numbers decided to appear twice, making the list longer! 😅 My task was to find those two sneaky numbers and bring peace back to Digitville. 📘 Example: Input: nums = [0,3,2,1,3,2] Output: [2,3] Explanation: Numbers 2 and 3 appear twice in the array. 🧠 My Thought Process: At first, I thought of sorting the array and checking adjacent elements, but that would take O(n log n) time. Then I realized I could just keep track of which numbers I’ve seen using a boolean array — whenever I see a number again, that’s one of the sneaky ones! Since n ≤ 100, a simple O(n) solution works perfectly here. 💻 Code (Java): class Solution { public int[] getSneakyNumbers(int[] nums) { int n = nums.length - 2; boolean[] seen = new boolean[n]; int[] result = new int[2]; int idx = 0; for (int num : nums) { if (seen[num]) { result[idx++] = num; if (idx == 2) break; } else { seen[num] = true; } } return result; } } 🔍 Dry Run Example: nums = [0,3,2,1,3,2] Start → seen = [F,F,F,F] See 0 → mark as true See 3 → mark as true See 2 → mark as true See 1 → mark as true See 3 again → duplicate #1 See 2 again → duplicate #2 ✅ Output → [3,2] (order doesn’t matter) ⚙️ Complexity: Time: O(n) Space: O(n) Simple, clean, and efficient! 🎯 Key Learnings: Reinforced how boolean arrays can efficiently handle duplicates. Learned to identify when sorting isn’t needed — sometimes direct logic is faster. Keeping things simple often gives the most elegant solutions. 🗓️ LeetCode Streak: Day 7 / Small Steps → Big Progress 🚀 Each day I’m learning new ways to look at problems — this one taught me simplicity is power 💪 #LeetCode #100DaysOfCode #Java #DSA #ProblemSolving #LearningJourney #CodingPractice #DeveloperLife
Solved LeetCode problem: Find the Two Sneaky Numbers with boolean array
More Relevant Posts
-
https://lnkd.in/gmysJzSq Today I solve the classic tree-recursion problem on LeetCode: “Same Tree”. The task was to determine if two binary trees are structurally identical and have the same node values. What I did Handled base cases: if both nodes are nullptr, return true; if one is nullptr and the other isn’t, return false. Recursively compared the left subtrees and right subtrees. Checked the current node values after the recursive calls. Ensured the solution is clean, simple, and efficient in terms of logic. Here’s the core solution snippet: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if (p == nullptr && q == nullptr) return true; if (p == nullptr || q == nullptr) return false; bool leftSame = isSameTree(p->left, q->left); bool rightSame = isSameTree(p->right, q->right); return (p->val == q->val) && leftSame && rightSame; } }; Key Takeaways Recursive tree problems often boil down to base case checks + recursive calls on subtrees + combining results. Clean code is powerful: Fewer lines, clear logic, fewer errors (e.g., mis-using -> vs >). Regularly solving such problems builds strong fundamentals for more complex tree or graph challenges later on. #LeetCode #Cplusplus #TreeAlgorithm #DSA #ProblemSolving #CodingJourney #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
I spent way too much time on Leetcode 219. Not because it's hard. But because my brain immediately cooked up the dumbest possible solution. The Problem: "Find a duplicate number... but only if it's close to another one." (i.e., nums[i] == nums[j] and abs(i - j) less= k). My Brain: "Easy! I'll just check every. single. number. And for each one, I'll check the next k numbers to see if there's a match." This is the O(n∗k) solution. It's the code equivalent of trying to find a matching sock by taking one sock, comparing it to the next 5 in the drawer, then putting it down, picking up the next sock, and comparing that one to the 5 after it. My poor laptop fan sounded like it was preparing for takeoff. ✈️ It's slow. It's ugly. It's the "Brute Force" method, which is a polite way of saying "I have no new ideas and I'm mad about it." Then, the "aha" moment. Why am I re-checking everything? Why not just... remember? Enter the hero of our story: The Hash Map (aka the Python Dictionary). The Hash Map is like a bouncer at a club, but one with a perfect memory. Instead of that nested-loop nightmare, you do one. single. pass. You walk up to each number in the array. You: "Hey, bouncer. Seen this '7' before?" Bouncer (Hash Map): "Nope. First time. I'll write him down. He's at spot 3." (You add {7: 3} to the map) ...you keep going... You: "How about this '7' at spot 8?" Bouncer: "Hold up. Yeah, I've definitely seen that guy. He was just here at spot 3." You: "Is spot 8 'close' to spot 3?" (Is 8 - 3 less= k?) Bouncer: "Yeah, that's close enough." You: "BINGO. return True." And if the '7' wasn't close enough? You: "Alright, well, he's here now. Update your list." (Bouncer crosses out spot 3 and writes spot 8. You update the map: {7: 8}) That's it. We just took a clunky, grinding O(n∗k) mess and turned it into a sleek, lightning-fast O(n) masterpiece. All by using the right tool for the job. It’s not just about getting the right answer. It’s about getting it without making your computer cry. I made a full video walking through this exact "Brute Force to Optimal" journey. We build the bad one, feel the shame, and then build the Hash Map hero. What's a "simple" problem that totally tricked you at first? #leetcode #python #coding #softwareengineering #problemsolving #dsa #datastructures #algorithms #hashmap #optimization #funny #techhumor
To view or add a comment, sign in
-
#100DaysCodingChallenge #Day41 Question : #Problem 205 in Leet Code : Isomorphic Strings Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. Example 1: Input: s = "egg", t = "add" Output: true Explanation: The strings s and t can be made identical by: Mapping 'e' to 'a'. Mapping 'g' to 'd'. Example 2: Input: s = "foo", t = "bar" Output: false Explanation: The strings s and t can not be made identical as 'o' needs to be mapped to both 'a' and 'r'. Example 3: Input: s = "paper", t = "title" Output: true Explanation : 🚀 Problem Solved: Isomorphic Strings (Java) Today I solved an interesting problem — checking if two strings are isomorphic. 💡 Problem Understanding Two strings s and t are said to be isomorphic if the characters in s can be replaced to get t, while preserving the order of characters. Every unique character in s must map to a unique character in t. The mapping should be consistent throughout both strings. ✅ Example: s = "egg", t = "add" → Isomorphic (e→a, g→d) s = "foo", t = "bar" → Not Isomorphic s = "paper", t = "title" → Isomorphic 🧠 Approach Explanation To determine if two strings are isomorphic, we need to ensure: Each character in s maps to exactly one character in t. The reverse should also hold true — each character in t maps to only one in s. I divided the logic into two steps: Step 1: Create a mapping from characters of s → t using a HashMap. If a character is already mapped, check if the new mapping remains consistent. If not, the strings are not isomorphic. Step 2: Repeat the process from t → s to ensure the mapping is bijective (one-to-one and onto). Finally, if both mappings are valid, the strings are isomorphic. 🔍 Key Highlights Used a HashMap<Character, Character> to store the character mapping efficiently. Checked both forward and reverse mappings to prevent invalid one-way mappings. Time Complexity → O(n) (single pass over the string). Space Complexity → O(1) (since only character mappings are stored). 🎯 Takeaway This problem strengthened my understanding of hashing, string manipulation, and bijection logic in programming. It also showed how thinking in two directions (s → t and t → s) ensures the correctness of the mapping. #100DaysCodingChallenge #problemsolving #java #Day41 10000 Coders karunakar pusuluri Rudra Sravan kumar Manoj Kumar Reddy Parlapalli
To view or add a comment, sign in
-
-
https://lnkd.in/gYKr9A3J Today I solved an interesting Binary Tree problem on LeetCode: “Subtree of Another Tree”. The task was to determine whether one binary tree (subRoot) is a subtree of another (root). This problem reinforced the importance of recursion and tree traversal techniques. My Approach: Wrote a helper function isIndentical to check if two trees are exactly the same. In isSubtree, recursively checked for every node in the main tree whether the subtree matches. Carefully handled null cases to avoid runtime errors. Here’s my C++ implementation: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isIndentical(TreeNode* p, TreeNode* q){ if(p == NULL && q == NULL) return true; if(p == NULL || q == NULL) return false; return p->val == q->val && isIndentical(p->left, q->left) && isIndentical(p->right, q->right); } bool isSubtree(TreeNode* root, TreeNode* subRoot) { if(root == NULL) return false; if(isIndentical(root, subRoot)) return true; return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot); } }; Key Takeaways: Recursion is a powerful tool for tree problems. Always handle null cases carefully to avoid runtime errors. Writing a clean helper function can simplify complex problems. #LeetCode #CPlusPlus #BinaryTree #DSA #ProblemSolving #CodingJourney #TreeAlgorithms #SoftwareEngineering
To view or add a comment, sign in
-
LeetCode 104 – Maximum Depth of a Binary Tree 🌳 Today I solved one of the classic problems in data structures: “Given the root of a binary tree, return its maximum depth.” 👉 What’s a binary tree? A binary tree is a hierarchical structure where each node has at most two children: left and right. The maximum depth is simply the longest path from the root down to the farthest leaf. 🧩 Why Recursion Works Best Trees are naturally recursive: Each node is itself the root of a smaller subtree. To solve the whole tree, you solve the left subtree and the right subtree, then combine results. This makes recursion elegant and intuitive compared to iterative approaches. ✅ My Solution public int maxDepth(TreeNode root) { if (root == null) return 0; int leftDepth = maxDepth(root.left); int rightDepth = maxDepth(root.right); return 1 + Math.max(leftDepth, rightDepth); } 📊 Complexity Time: O(n) → we visit every node once. Space: O(h) → recursion stack depends on tree height. Worst case (skewed tree): O(n) Best case (balanced tree): O(log n) 🎯 Key Takeaway Binary trees are a perfect example of why recursion is powerful. Once you “think recursively,” problems like maximum depth become straightforward. This problem reminded me that elegance in code often comes from matching the solution to the structure of the data. #LeetCode #DataStructures #BinaryTree #Recursion #Java #CodingJourney
To view or add a comment, sign in
-
-
🌳 Day 96 – Binary Tree Paths Challenge! 🌟 Today’s challenge is a beautiful recursion and DFS problem that teaches how to traverse a binary tree while maintaining dynamic path information. It’s an elegant example of how recursive backtracking helps build all possible paths from root to leaf! 🌿✨ 🔹 Problem: Binary Tree Paths (LeetCode 257) 🧩 Given: The root of a binary tree. 📥 Return: All root-to-leaf paths in the tree as strings — where each path is represented as "node1->node2->...->leaf". 📘 Example: Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: Path 1: 1 → 2 → 5 Path 2: 1 → 3 Both are valid root-to-leaf paths. ⚡ Approach: Depth-First Search (DFS) with Path Building 1️⃣ Start from the root node with an empty path string. 2️⃣ At each node: Add the current node’s value to the path. If it’s a leaf node, store the path in the result list. Otherwise, continue recursively to the left and right child, appending "->" to indicate continuation. 3️⃣ End Condition: Stop recursion when both children are null. 🧠 Key Insights: ✅ Each recursive call maintains its own version of the path string (no manual backtracking needed). ✅ String concatenation (ans + "->") creates a clean path structure. ✅ The traversal ensures O(N) time, visiting each node exactly once. ✅ A perfect mix of recursion, string manipulation, and tree traversal. 📉 Complexity Analysis ⏱ Time Complexity: O(N) — each node is processed once. 💾 Space Complexity: O(H) — recursion stack depth equals the height of the tree. 🔗 LeetCode Problem: 257 - Binary Tree Paths - https://lnkd.in/gA-YgATx 📂 Code Implementation: https://lnkd.in/g55-Cuhx 🚀 Day 96 Completed! ✔️ Strengthened understanding of recursive tree traversal. ✔️ Practiced path construction from root to leaf. ✔️ Reinforced base case + recursion pattern for binary trees. ✔️ One step closer to mastering tree-based DFS problems! #Day96 #DSAChallenge #100DaysOfDSA #BinaryTree #DFS #Recursion #Backtracking #LeetCode #ProblemSolving #JavaDeveloper #FullStackDeveloper #CodingChallenge #SoftwareEngineering #GrowthMindset #OpenToWork #Hiring
To view or add a comment, sign in
-
-
𝗧𝗲𝗷ú 𝗝𝗮𝗴𝘂á: 𝘁𝗵𝗲 𝗰𝗮𝘀𝗲 𝗳𝗼𝗿 𝘀𝗺𝗮𝗹𝗹 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 I saw a post against splitting code into small functions, claiming they add unnecessary levels of indirection, making the code harder to read. The author added two exceptions where this practice is fine: when math is involved or the code is an algorithm. (I'm sure there are plenty more.) Tejú Jaguá is my float-to-string conversion algorithm and involves math. Hence, it's a perfect example of the author's accepted exceptions. The next paragraph describes a part of the algorithm in high-level terms. This is the same kind of overview, almost in plain English, presented in my introductory talks. (🔗 in comments.) Tejú Jaguá returns an approximation n × 10ᶠ for the input m × 2ᵉ (m, e, n and f are integers.) After finding f, it seeks n. Occasionally, it finds a candidate n = b that yields a tie, i.e. b × 10ᶠ is halfway between m × 2ᵉ and the next possible input (m + 1) × 2ᵉ. In this case, b × 10ᶠ should be returned only if m wins a tiebreak against m + 1. (Otherwise, b × 10ᶠ is reserved for (m + 1) × 2ᵉ.) Below is the complete decision logic. (Never mind the entities which I didn't provide a definition for. Just bear with me.) 𝚒𝚏 (𝚏 >= 0 && 𝚏 <= 𝚜𝚒𝚣𝚎𝚘𝚏(𝙼) / 𝚜𝚒𝚣𝚎𝚘𝚏(𝙼[0]) && 𝚖_𝚋 * 𝙼[𝚏] < 𝙱[𝚏] && 𝚖 % 𝟸 == 0) I couldn't read this code just a few days after I wrote it. This reminded me of Scott Meyers, in Effective STL, telling us to avoid producing "write-only" code. So, I factored out two functions and changed the above to: 𝚒𝚏 (𝚒𝚜_𝚝𝚒𝚎(𝚏, 𝚖_𝚋) && 𝚠𝚒𝚗𝚜_𝚝𝚒𝚎𝚋𝚛𝚎𝚊𝚔(𝚖)) This code is far easier to understand and very close to the high-level description above. It 𝘵𝘦𝘭𝘭𝘴 𝘢 𝘴𝘵𝘰𝘳𝘺 that may be enough for most readers. If not, one can dig deeper and find: 𝚋𝚘𝚘𝚕 𝚠𝚒𝚗𝚜_𝚝𝚒𝚎𝚋𝚛𝚎𝚊𝚔(𝚞𝚗𝚜𝚒𝚐𝚗𝚎𝚍 𝚖) { 𝚛𝚎𝚝𝚞𝚛𝚗 𝚖 % 𝟸 == 0; } This function checks if m is even and, accordingly, could be called 𝚒𝚜_𝚎𝚟𝚎𝚗 but this wouldn't be helpful. At this high-level context, it's far more important to say that we're running the tiebreak. The parity test is a lower-level point for those who need to see it. Also, context matters: 𝚠𝚒𝚗𝚜_𝚝𝚒𝚎𝚋𝚛𝚎𝚊𝚔 should be logically close to the algorithm (e.g. in the same file.) If it was in a far away generic utility file with no usability context, then it should be renamed 𝚒𝚜_𝚎𝚟𝚎𝚗. (Arguably, it shouldn't exist but, for the sake of the argument, let's suppose it does.) Then, close to the algorithm we should have: 𝚋𝚘𝚘𝚕 𝚠𝚒𝚗𝚜_𝚝𝚒𝚎𝚋𝚛𝚎𝚊𝚔(𝚞𝚗𝚜𝚒𝚐𝚗𝚎𝚍 𝚖) { 𝚛𝚎𝚝𝚞𝚛𝚗 𝚒𝚜_𝚎𝚟𝚎𝚗(𝚖); } Another one-liner that just calls yet another one. Why bother? Because of the context change and the point already explained. A similar story holds for 𝚒𝚜_𝚝𝚒𝚎. I'm sure small functions can bring clarity to a lot of code out there. Stay tuned. Please follow me, like this post and share it with your network. #algorithms #mathematics #floatingpoint
To view or add a comment, sign in
-
-
🚀 Day 43 of #100DaysOfCode – LeetCode Problem #2460: Apply Operations to an Array 💬 Problem Summary: You’re given a non-negative integer array nums. You need to: Sequentially check each element nums[i]. If nums[i] == nums[i + 1], then: Multiply nums[i] by 2 Set nums[i + 1] to 0 After all operations, move all zeros to the end of the array. Return the resulting array. 🧩 Example: Input: [1,2,2,1,1,0] Output: [1,4,2,0,0,0] Explanation: - i=1: 2 == 2 → [1,4,0,1,1,0] - i=3: 1 == 1 → [1,4,0,2,0,0] Shift zeros → [1,4,2,0,0,0] 🧠 Logic: ✅ Traverse the array once, applying the doubling rule. ✅ Use a two-pointer approach or list building to shift zeros efficiently. 💻 Java Solution: class Solution { public int[] applyOperations(int[] nums) { int n = nums.length; for (int i = 0; i < n - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } int index = 0; for (int num : nums) { if (num != 0) nums[index++] = num; } while (index < n) { nums[index++] = 0; } return nums; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 💬 Takeaway: This problem reinforces the importance of in-place transformations and efficient data movement.
To view or add a comment, sign in
-
Day 13 of My #JavaWithDSA Challenge — Sorting 0s, 1s, and 2s Today’s problem from GeeksforGeeks was a classic array sorting challenge — “Sort an array of 0s, 1s, and 2s without using any built-in sorting function.” It’s often known as the Dutch National Flag problem, and it beautifully demonstrates how to solve sorting problems in a single pass (O(n)) using only constant space (O(1)). Problem Statement Given an array arr[] containing only 0s, 1s, and 2s — sort it in ascending order without using the built-in sort() function. Example: Input: arr[] = [0, 1, 2, 0, 1, 2] Output: [0, 0, 1, 1, 2, 2] Concept: Dutch National Flag Algorithm The main idea is to maintain three pointers: low → points to where the next 0 should go mid → current element being checked high → points to where the next 2 should go We use these rules: If arr[mid] == 0: swap with arr[low], move both low and mid forward. If arr[mid] == 1: just move mid forward. If arr[mid] == 2: swap with arr[high], move high backward. This ensures that: All 0s are placed before low, All 1s are between low and high, All 2s are after high. Code Implementation (Java) class Solution { public void sort012(int[] arr) { int low = 0, mid = 0, high = arr.length - 1; while (mid <= high) { if (arr[mid] == 0) { int temp = arr[low]; arr[low] = arr[mid]; arr[mid] = temp; low++; mid++; } else if (arr[mid] == 1) { mid++; } else { int temp = arr[mid]; arr[mid] = arr[high]; arr[high] = temp; high--; } } } } Time & Space Complexity Time: O(n) → single traversal Space: O(1) → constant extra space Key Takeaways Understanding pointer manipulation can eliminate the need for extra space. The Dutch National Flag algorithm is a must-know for array partitioning problems. Writing efficient code often means thinking logically, not relying on built-in functions. #JavaWithDSA #GeeksforGeeks #CodingChallenge #DSA #LearningInPublic #WomenInTech #JavaDeveloper #ProgrammingJourney
To view or add a comment, sign in
-
-
Today, I solved LeetCode Problem #987 – Vertical Order Traversal of a Binary Tree. This problem is quite similar to the Top View of Binary Tree, but with a twist — we must print all nodes column by column, sorted by their vertical and level order positions. Problem Summary: Given the root of a binary tree, we need to return its vertical traversal — where nodes are grouped by their x-coordinate (column) and sorted: By row (y) in ascending order If two nodes share the same position, by node value Approach (Using find()): Perform a BFS traversal, keeping track of each node’s (x, y) coordinates. Store nodes in a map<int, vector<pair<int,int>>>, where x = column index. Use map.find(x) to check if a column exists before inserting values. Sort nodes in each column based on (y, val), and then build the final result. Time Complexity: O(N log N) Space Complexity: O(N) C++ Code: class Solution { public: vector<vector<int>> verticalTraversal(TreeNode* root) { if(!root) return {}; map<int, vector<pair<int,int>>> mp; queue<pair<TreeNode*, pair<int,int>>> q; q.push({root, {0, 0}}); while(!q.empty()){ auto p = q.front(); q.pop(); TreeNode* node = p.first; int x = p.second.first, y = p.second.second; auto it = mp.find(x); if(it == mp.end()) mp[x] = vector<pair<int,int>>(); mp[x].push_back({y, node->val}); if(node->left) q.push({node->left, {x - 1, y + 1}}); if(node->right) q.push({node->right, {x + 1, y + 1}}); } vector<vector<int>> ans; for(auto &it : mp){ auto &vec = it.second; sort(vec.begin(), vec.end(), [](auto &a, auto &b){ if(a.first == b.first) return a.second < b.second; return a.first < b.first; }); vector<int> col; for(auto &p : vec) col.push_back(p.second); ans.push_back(col); } return ans; } }; Concepts Covered: Binary Tree Traversal BFS with Coordinates Map + Sorting Efficient column lookup using find() Platform: LeetCode Problem Link: Vertical Order Traversal of a Binary Tree: https://lnkd.in/gi_5C6wE
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