🚀 Day 17 — Valid Parentheses Continuing the Stack pattern. 🧩 Problem solved: Valid Parentheses 💻 Platform: LeetCode (#20) Given a string containing only '(', ')', '{', '}', '[' and ']', determine if the input string is valid. Example: Input: s = "()[]{}" Output: true Input: s = "([)]" Output: false --- 🧠 First Thought (Brute Force) Repeatedly remove adjacent matching pairs like "()", "[]", "{}" until no more removals are possible. If the string becomes empty → valid. But this leads to O(n²) complexity. Clearly inefficient. --- ⚡ Optimal Approach — Stack (via StringBuilder) Key Insight: A closing bracket must always match the most recently seen opening bracket. That’s exactly what a Stack is built for — LIFO. Twist: Instead of Stack<Character>, I used StringBuilder as the stack. Same logic, lighter overhead. Steps: • Iterate through each character • If top of StringBuilder matches current closing bracket → pop (deleteCharAt) • Otherwise → push (append) • If StringBuilder is empty at end → valid Time Complexity: O(n) Space Complexity: O(n) 🔍 What this problem reinforced: ✔ Stack is the go-to structure when order + matching matters ✔ LIFO logic maps perfectly to nested bracket structures ✔ StringBuilder can simulate a stack — not just for string building! This problem made the Stack pattern click in a new way. Solutions are available here: 🔗https://lnkd.in/gW8atfqw Day-17 complete. ✅ #DSA #Java #LeetCode #Stack #ProblemSolving #CodingJourney #LearningInPublic
Valid Parentheses Problem Solution with Stack
More Relevant Posts
-
🚀Day 98 of construct Binary search Tree from Preorder traversal. The Problem given an Array of Integers preorder, which represents the preorder traversal of BST (i.e., binary search Tree) construct the tree and return it's root guaranteed that there is always possible to find a binary tree with the given requirements for the given taste cases. Brute force - sort the preorder array to get inorder traversal, then use both preorder and inorder arrays to reconstruct the BST) ( like standard tree construction.) this gives O(n log n ) time due to sorting, which is inefficient when BST properties can guide direct construction. Approach used - •) if order. length ==0, return null ( empty tree). •) create root with first element, root = new tree node (Preorder [0]). •) return root. Helper function - insert Treenode root int val) •if val < root. val , insert in left subtree, - if root.left == null, create node , root left = new tree node( val). - Else recurse left , insert (root, left, val). •) Else ( when Val > root Val ), insert in right subtree, - if root. right == null, crate node , root right = new Tree node ( val ) - Else , recurse right , insert ( root. right, val ). complexity Time - O ( n × h ) , where h = height of tree is a number of nodes. Space - O( h), recursion stack depth. Note - preorder traversal's first element is always the root. By leveraging BST insertion rules . ( smaller values go left , larger go right ), we can sequentially insert each element from the preorder array. each insertion automatically finds the correct position building the BST without needing inorder traversal or sorting. #Java #LearnToCode #Problemsolving #DSA #coding
To view or add a comment, sign in
-
-
Solved LeetCode Medium – 1536. Minimum Swaps to Arrange a Binary Grid today! 💻 Instead of actually swapping rows in the grid, I optimized the solution by tracking trailing zero counts per row and performing swaps on that array. This significantly simplifies the implementation and improves readability. Approach I Followed 1. Count Trailing Zeroes in Each Row For each row in the grid, traverse from the rightmost column. Count how many continuous zeroes appear at the end of that row. Store these counts in an array zeroes[i]. Example: Row: [1,0,0,0] → trailing zeroes = 3 Row: [1,1,0,0] → trailing zeroes = 2 2. Determine Required Zeroes per Row For row i, we need at least: requiredZeroes = n - i - 1 Because every row above must have enough zeros so that all elements above the main diagonal are zero. 3. Find a Suitable Row Search for the first row j ≥ i that has enough trailing zeroes. If no such row exists → return -1 (arrangement impossible). 4. Bring That Row Up Using Adjacent Swaps Swap row j upward until it reaches position i. Each adjacent swap increases the swap count. Instead of swapping rows in the grid, swap values in the zeroes array. This simulates the required row movement efficiently. 5. Continue Until Grid is Valid Repeat for every row until all constraints are satisfied. ✅ Time Complexity: O(n²) ✅ Space Complexity: O(n) It was a great exercise in greedy thinking, array manipulation, and edge-case handling. Always satisfying to break down a tricky grid problem into a simpler representation! 🚀 #LeetCode #DSA #Java #CodingPractice #GreedyAlgorithm #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
🔥 Day 552 of #750DaysOfCode 🔥 🔐 LeetCode 2075: Decode the Slanted Ciphertext (Medium) Today’s problem looked tricky at first, but once the pattern clicked, it became super elegant 😄 🧠 Problem Understanding We are given an encoded string that was: Filled diagonally (↘) into a matrix Then read row-wise (→) 👉 Our task is to reverse this process and recover the original text. 💡 Key Insight If encoding is: ➡️ Fill diagonally ➡️ Read row-wise Then decoding is: ➡️ Read diagonally from row-wise string ⚙️ Approach ✅ Step 1: Calculate number of columns cols = encodedText.length() / rows; ✅ Step 2: Traverse diagonals starting from each column for (int startCol = 0; startCol < cols; startCol++) { int row = 0, col = startCol; while (row < rows && col < cols) { result.append(encodedText.charAt(row * cols + col)); row++; col++; } } ✅ Step 3: Remove trailing spaces 🚀 Complexity Time: O(n) Space: O(n) 🧠 What I Learned How to reverse matrix-based encoding patterns Converting 2D traversal → 1D index mapping Importance of pattern recognition in problems 📌 Takeaway Not every problem needs heavy logic. Sometimes, it's just about seeing the pattern correctly 👀 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Algorithms #SoftwareEngineering #100DaysOfCode #750DaysOfCode
To view or add a comment, sign in
-
-
Day 29/30 – LeetCode streak Problem: Fancy Sequence You need to support 'append', 'addAll', 'multAll', and 'getIndex' under modulo '(10^9 + 7)' in 'O(1)' per operation. Core idea Keep the logical sequence implicitly via a global affine transform: * Store an internal array 'vals[]'. * Maintain global coefficients 'mul = a' and 'add = b' so that for every index 'i': 'real_i ≡ a · vals[i] + b (mod M)' * Initially, 'a = 1' and 'b = 0', so the stored value equals the real value. Operations * 'append(val)' We want to store a value 'x' such that: 'a · x + b ≡ val (mod M)' Rearranging gives: 'x ≡ (val − b) · a⁻¹ (mod M)' Since 'M' is prime and 'a ≠ 0', the modular inverse 'a⁻¹' exists and can be computed using Fermat’s little theorem. * 'addAll(inc)' Adding a constant to every element changes the transform: 'a · x + b → a · x + (b + inc)' So we simply update: 'add = (add + inc) % MOD'. * 'multAll(m)' Multiplying every element scales both coefficients: 'a · x + b → (a · m) · x + (b · m)' So update: 'mul = (mul * m) % MOD' 'add = (add * m) % MOD'. * 'getIndex(idx)' If the index is out of range return '-1'. Otherwise compute the real value using the stored transform: 'real = (mul * vals[idx] + add) % MOD'. Day 29 takeaway: Instead of updating every element on each operation, using a lazy affine transformation 'a · x + b' lets you represent the entire sequence with just two parameters, turning what would normally be 'O(n)' updates into constant-time operations. #leetcode #dsa #java #math #design #consistency
To view or add a comment, sign in
-
-
HI CONNECTIONS I recently tackled LeetCode 960, the most challenging installment in the "Delete Columns" series. This problem transforms from a simple array check into a Longest Increasing Subsequence (LIS) problem across multiple strings. 🔍 The Challenge We need to delete the minimum number of columns so that every single string in the array is in lexicographical order. The Goal: Minimize deletions \rightarrow Maximize the number of columns we keep. The Constraint: For any two columns we keep (j and i, where j < i), every string must satisfy row[j] <= row[i]. 🛠️ My Approach: Multi-String Dynamic Programming This is essentially finding the "Longest Increasing Subsequence" that is valid for all rows simultaneously. Define DP State: Let dp[i] be the maximum number of columns we can keep ending at column i. The Comparison: To transition from dp[j] to dp[i], we must check every row. If for all rows, row[j] <= row[i], then column i can follow column j. The Formula: dp[i] = \max(dp[i], dp[j] + 1) for all j < i. Final Calculation: The minimum deletions = Total Columns - max(dp). 📊 Efficiency Time Complexity: O(K^2 \times N) — Where K is the length of the strings (number of columns) and N is the number of strings. We compare every pair of columns across all rows. Space Complexity: O(K) — To store the dp array. 💡 Key Takeaway This problem beautifully demonstrates how a 1D Dynamic Programming pattern (LIS) can be adapted to multi-dimensional constraints. When you can't solve a problem greedily, looking for the "Longest Subsequence" is often the path to the optimal solution. #LeetCode #DynamicProgramming #AlgorithmDesign #SoftwareEngineering #ProblemSolving #CodingInterviews
To view or add a comment, sign in
-
-
LeetCode 2130 — Maximum Twin Sum of a Linked List This problem gives the head of a linked list with even length. For a list of size n, the iᵗʰ node and the (n−1−i)ᵗʰ node are considered twin nodes. The twin sum is defined as the sum of the values of these two nodes. The task is to return the maximum twin sum in the linked list. Example : Input : 5 → 4 → 2 → 1 Twin pairs : (5,1) → sum = 6 (4,2) → sum = 6 Output : 6 Approach used — Reverse Second Half + Twin Traversal Because twin nodes lie symmetrically from the start and end, the list can be processed efficiently by reversing half of it. Two main steps are used during traversal. • First, fast and slow pointers are used to locate the middle of the linked list. - slow moves one step at a time. - fast moves two steps at a time. When fast reaches the end, slow will be positioned at the start of the second half. • The second half of the list is then reversed so that twin nodes align during traversal. After reversing : - One pointer starts from the beginning of the list. - Another pointer starts from the reversed second half. At each step : - The twin sum is calculated. - The maximum twin sum is updated. This approach works in O(n) time and O(1) extra space. #leetcode #datastructures #linkedlist #java #problemSolving
To view or add a comment, sign in
-
-
Day 43: Interactive Logic & Flow Control – Jumping Statements & Scanner 🏃♂️⌨️ Today’s session was a "Power Move" in Java, focusing on how to break the rules of loops and give the user a voice through the console. 1. The "Escape Routes": Jumping Statements 🦘 Loops are powerful, but sometimes you need to override them. I mastered the two primary ways to manipulate execution flow: ▫️ break: The "Emergency Exit." It terminates the loop immediately. This is essential for optimization—once you find the data you're looking for, why keep searching? ▫️ continue: The "Skip Button." It bypasses the rest of the current code block and jumps straight to the next iteration. Perfect for filtering out specific data points without stopping the whole process. 2. The "User Input": Scanner Class 📥 Hardcoding values is a thing of the past! Using java.util.Scanner, I transformed my programs into interactive tools that can talk to the user: ▫️ Dynamic Data: Using next(), nextInt(), and nextLine() to capture real-time input directly from the keyboard. ▫️ The Workflow: I practiced the standard cycle: Import ➡️ Initialize Object ➡️ Prompt User ➡️ Capture ➡️ Process. 3. The "Buffer" Lesson: Precision Coding ⚠️ A key technical takeaway today was handling the "NextLine Trap." I learned how to properly clear the buffer after using nextInt() to ensure the program doesn't skip over string inputs. It’s these small details that separate a beginner from a professional! The Java logic is getting sharper, and the programs are getting smarter. 🧩 Next up: Nested Loops and Logic Patterns! 🚀 #JavaFullStack #100DaysOfCode #BackendDevelopment #JavaScanner #CodingLogic #SoftwareEngineer #ChirukuriNarendra #LearningInPublic
To view or add a comment, sign in
-
Your custom Frappe REST API endpoint is probably duplicating authentication logic you don't need. Many engineers building integrations often re-verify user tokens or session validity inside custom Frappe methods. This is redundant and introduces unnecessary complexity. 💡 Leverage `frappe.auth.get_logged_user()` directly within your custom `frappe.whitelist()` method. It handles session validation and returns the current user ID, or raises `frappe.throw` if unauthorized. Before: Manually parsing headers, validating JWTs, and querying 'User' doctype. ❌ After: A single call to `frappe.auth.get_logged_user()` for robust, built-in validation. ✅ This pattern simplifies custom endpoint development significantly, reducing boilerplate by 30-40% and improving maintainability. For Frappe V14+, always check `frappe.auth` utils. ⚙️ What's your go-to Frappe server-side utility that significantly reduced your development effort? #FrappeFramework #RESTAPI #FrappeDevelopment #Python #WebDevelopment #Frappe #ERPNext #Tech
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟑𝟔 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on converting a sorted array into a height-balanced Binary Search Tree (BST). 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Convert Sorted Array to Binary Search Tree 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • Since the array is sorted, the middle element naturally becomes the root • Elements on the left side form the left subtree • Elements on the right side form the right subtree • Recursively applied the same logic to both halves This ensures the tree remains height-balanced. 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Sorted arrays are perfect for constructing balanced BSTs • Choosing the middle element maintains balance • Divide-and-conquer simplifies tree construction • Recursion helps build hierarchical structures naturally 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(n) • Space: O(log n) (recursion stack) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Sometimes the structure of the input already hints at the best tree structure. 36 days consistent 🚀 On to Day 37. #DSA #Arrays #BinarySearchTree #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
I had 171 lines in my CLAUDE.md file. That file loads at the start of every session. Every prompt, every response, every quick question. 171 lines of context, whether I needed it or not. That's roughly 5,800 tokens burned before Claude even reads what I'm asking. I didn't notice because the system still worked. But I was carrying business strategy context while debugging a CSS issue. Loading content pipeline rules while writing a Python script. Paying for context I wasn't using. So I split everything into two categories: what Claude needs on literally every message, and what it only needs sometimes. CLAUDE.md went from 171 lines to 82. Just identity, workspace structure, and pointers. The full context (business model, content system, routines) moved into separate files that load on demand through a /prime skill. Rules files went from 240 lines to 7. They're just triggers now. "When X happens, read Y." The full procedures live somewhere else. Results: 64% fewer tokens loaded per message. Everything still works exactly the same. When I need the full picture, I type /prime and it loads in parallel. When I'm just writing code, I don't carry the weight. Simple idea but easy to miss. If you're building with Claude Code, check how big your CLAUDE.md is. Every line in there compounds across hundreds of messages a day. How are you structuring yours?
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