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
More Relevant Posts
-
✨ 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
To view or add a comment, sign in
-
-
🚀 Day 12 — LeetCode #49: Group Anagrams I solved #LeetCode49 using a hash map with a character-count key (O(N·K) time). Instead of sorting each string, I used a fixed 26-length tuple of character counts as the dictionary key — faster when strings get long. 💡 Solution idea: For each word create a 26-entry count tuple and group words with the same tuple. 🧩 Challenge for you: Which approach would you pick and why? A — Sort each string (simple & intuitive) B — Character-count tuple (O(N·K), great for long words) C — Other (prime-hash, multiset, language-specific tricks) — share below! Drop your choice in the comments and paste your implementation (or a one-liner)! I'll feature interesting takes and explain trade-offs. #100DaysOfCode #DataStructures #Algorithms #C++ #LeetCode
To view or add a comment, sign in
-
-
#120DaysChallenge #Day9 🔸 Sets and set methods Set: A set is an unordered collection of unique elements. ▫️ We will Define Set in Curly Braces {} ▫️ It is Semi mutable ▪️ They are 19 list methods #sets {} a= {8,9.0,"python",4+8j, True} a {True, 8, 9.0, (4+8j), 'python'} type(a) <class 'set'> #issubset () a={1,2,3,4,5} b={3,4,5} b.issubset (a) True a.issubset (b) False #issuperset () a={4,5,6,7,8} b={5,6,7} a.issuperset (b) True b.issuperset (a) False #add () a={10,20,30} a.add(60) a {10, 20, 30, 60} #intersection () a={1,2,3,4,5} b={3,4,5,6} a.intersection(b) {3, 4, 5} b.intersection(a) {3, 4, 5} #union () a= {1,2,3,4,5} b= {5,6,7,8,9} a.union(b) {1, 2, 3, 4, 5, 6, 7, 8, 9} b.union(a) {1, 2, 3, 4, 5, 6, 7, 8, 9} a {1, 2, 3, 4, 5} #update () a= {2,3,4,5,6} b= {3,4,5,6,7,8} a.update(b) a {2, 3, 4, 5, 6, 7, 8} a {2, 3, 4, 5, 6, 7, 8} b.update (a) b {2, 3, 4, 5, 6, 7, 8} #difference () a= {1,2,3,4,5,7} b= {4,3,7,9,10,8} a.difference(b) {1, 2, 5} b.difference(a) {8, 9, 10} #intersection_update () a= {2,4,6,8} b= {1,2,3,4,5} a.intersection_update (b) a {2, 4} b.intersection_update(a) b {2, 4} #difference_update () a= {2,4,6,8,10} b= {6,8,10,1,3} a.difference_update(b) a {2, 4} b.difference_update(a) b {1, 3, 6, 8, 10} #symmetric_difference () a= {1,2,3,4,5,6,7} b= {6,7,8,9,10,12} a.symmetric_difference(b) {1, 2, 3, 4, 5, 8, 9, 10, 12} a {1, 2, 3, 4, 5, 6, 7} b.symmetric_difference(a) {1, 2, 3, 4, 5, 8, 9, 10, 12} #symmetric_difference_update () a= {10,11,12,14,16} b= {11,12,16,17,18} a.symmetric_difference_update(b) a {17, 18, 10, 14} b.symmetric_difference_update(a) b {16, 10, 11, 12, 14} #pop a= {2,3,5,6,7} b= {1,5,8,9,10} a.pop () 2 #Remove () a.remove (3) a {5, 6, 7} #copy a= {4,6,8,2} a.copy() {8, 2, 4, 6} #clear () a= {1,2,3,4,5} a.clear() a set () b=set () b.add(77) b {77} #discard a= {1,2,3,4,5} a.discard(3) a {1, 2, 4, 5} #isdisjoint a= {1,2,3,4,5} b= {6,7,8,9,10} a.isdisjoint(b) True #len a= {2,3,4,5,6,4} len(a) 5 Codegnan!Pooja Chinthakayala
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
-
-
Today I spent some time improving the code quality and maintainability of our data pipelines using Pylint — a simple but powerful tool that often gets overlooked in Data Engineering projects. 🔍 What is Pylint? Pylint is a Python static code analysis tool that checks for: 1. Code errors and bad practices 2. Style consistency (PEP8) 3. Unused imports or variables 4. Docstring and naming issues 5. Complexity and maintainability scores It’s like having a code reviewer that never gets tired — catching small issues before they become big problems. 🧩 Example 1: Bad vs Good Code ❌ Bad Code: def getdata(x,y): return x+y ✅ Good Code (Pylint-friendly): def get_data(x: int, y: int) -> int: """Return the sum of two numbers.""" return x + y ✅ Pylint flags missing docstrings, poor naming (getdata → get_data), and missing type hints — nudging you toward clean, readable code. 🧩 Example 2: Unused Imports ❌ Bad Code: import pandas as pd import numpy as np def square(x): return x * x ✅ Good Code: def square(x: int) -> int: """Return square of a number.""" return x * x ✅ Pylint detects that pandas and numpy aren’t used and suggests removing them — helping keep the code lightweight and efficient. 💡 Why This Matters for Data Engineers? We often discuss Spark, Snowflake, Hadoop, Kafka, and other big data technologies — but we rarely talk about code observability and quality. Yet, as our pipelines grow in complexity, maintainable, readable, and testable code becomes just as important as scalability and performance. Tools like Pylint, along with unit testing, type hints, and linting pipelines in CI/CD, make a huge difference in the long run. You can check the documentation here: https://lnkd.in/gUeMKzae 👨💻 Let’s remember — writing good data engineering code isn’t just about moving data fast, it’s about making it future-proof. #DataEngineering #Python #Pylint #CleanCode #SoftwareEngineering #Spark #Snowflake #CodeQuality #BestPractices #GenAi
To view or add a comment, sign in
-
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
-
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
-
I’ve released pytoon-codec, a small Python library that implements a TOON (Token-Oriented Object Notation) encoder/decoder for time series and nested event logs. The motivation is simple: a lot of LLM pipelines move structured data around as JSON, but TOON-style tabular blocks can be significantly more token-efficient while staying easy to read and post-process. The codec is opinionated towards common telemetry-style workloads. Time series are encoded as compact TOON tables (e.g. `metrics[1000]{ts,value}: …`), and nested event payloads are flattened into dotted column names (such as `payload.sensor`, `payload.room`, `user.id`). On the way back, the library can expand those dotted paths into nested dicts again, so your application code still works with normal Python structures. Unsupported shapes (like arrays nested deep inside objects) fail loudly with clear errors rather than silently degrading. You can find the project at: https://lnkd.in/d4EStR9C. If you’re experimenting with TOON for LLM prompts around metrics, logs, or sensor data, I’d be very interested in feedback, bug reports, and examples of how you’re using it.
To view or add a comment, sign in
-
🚀 Day 78 - 100DaysOfCode 1611. Minimum One Bit Operations to Make Integers Zero Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0. Return the minimum number of operations to transform n into 0. Use a loop to find the largest power of 2 (curr) that is ≤ n. Keep track of its position k. This identifies the leftmost 1 bit in n. Mathematical Formula for Powers of Two: For numbers like 1, 2, 4, 8, 16... (i.e., 2^k), the number of operations to make them 0 is: f(k) = 2^(k + 1) - 1 Divide the Number: Split n into two parts: The most significant bit: curr = 2^k The remaining part: n' = n XOR curr (This removes the highest bit from n.) Recursive Relationship: The answer for n is derived as: A(n) = f(k) - A(n') Here, f(k) = steps to reduce 2^k → 0 A(n') = steps to reduce the smaller remaining number to 0 Why Subtraction (−) Instead of Addition (+): Because n is already partially reduced compared to 2^k. Those smaller bits represent “progress,” so we subtract the steps already covered. Recursion: The function calls itself with the smaller number n'. This continues until n becomes 0. Bitwise Operations Used: << → left shift to compute powers of two (2^(k+1)). ^ → XOR to remove the highest set bit from n. Complexity: Time: O((log n)²) Space: O(log n) (recursion depth) 📌 #100DaysOfCode #Day78 #Leetcode Good rated question
To view or add a comment, sign in
-
-
Hi Everyone: #Day-08 Concept: Sets & set methods Today I have learned about set & set methods #Sets: set is an unordered collection of elements enclosed within a curly bracket and separated by commas. 1)set does not stores duplicate values The elements contained in a set must be of immutable type 2)sets are randomly ordered. Ex:>>> a={3, 5.5, 'python', 7+5j, True} >>>type(a) output:<class 'set'> #SetMethods() #issubset a={1,2,3,4,5,6} b={7,8,9,10} a.issubset(b) False a={2,3,4,5,6,7,8} b={6,7,8} b.issubset(a) True #issuperset a={4,5,6,7,8,9} b={7,8,9} a.issuperset(b) True b.issuperset(a) False #add a={10,20,0} a.add(50) a {0, 10, 20, 50} #intersection a={1,2,3,4,5} b={3,4,5,6,7} a.intersection(b) {3, 4, 5} b.intersection(a) {3, 4, 5} #union a={3,4,5,6,7} b={6,7,8,9,10} a.union(b) {3, 4, 5, 6, 7, 8, 9, 10} b.union(a) {3, 4, 5, 6, 7, 8, 9, 10} #update a={3,4,5,6,7} b={6,7,8,9,10} a.update(b) a {3, 4, 5, 6, 7, 8, 9, 10} b.update(a) b {3, 4, 5, 6, 7, 8, 9, 10} #difference a={1,2,3,4,5,6,7} b={3,5,7,9,10,11} a.difference(b) {1, 2, 4, 6} b.difference(a) {9, 10, 11} #intersection_update a={10,11,12,13,14,15} b={12,14,16,17,18} a.intersection_update(b) a {12, 14} b.intersection_update(a) b {12, 14} #symmetric_difference a={2,4,6,8,10,12,14} b={1,3,4,5,8,12,15} a.symmetric_difference(b) {1, 2, 3, 5, 6, 10, 14, 15} a {2, 4, 6, 8, 10, 12, 14} b.symmetric_difference(a) {1, 2, 3, 5, 6, 10, 14, 15} b {1, 3, 4, 5, 8, 12, 15} #symmetric_difference_update a={8,9,10,11,12,13,14,15} b={10,11,13,15,16,17} a.symmetric_difference_update(b) a {8, 9, 12, 14, 16, 17} b.symmetric_difference_update(a) b {8, 9, 10, 11, 12, 13, 14, 15} #pop a.pop() 3 a {4, 5, 6, 7, 8} #remove() a.remove(5) a {4, 6, 7, 8} #copy >>> a={6,7,8,9} >>> a.copy() {8, 9, 6, 7} #clear() >>> a.clear() >>> a set() Thank you Codegnan, Uppugundla Sairam Sir, Pooja Chinthakayala Mam, Saketh Kallepu Sir.
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