Day 94: Slanted Ciphertext & Loop Optimization 📟 Problem 2075: Decode the Slanted Ciphertext Today’s solve was a fun callback to the "ZigZag Conversion" problem I've tackled before. The challenge: read a string that was written diagonally across a matrix and then flattened into a single row. The Strategy: • Diagonal Traversal: The key is calculating the step size. In a slanted cipher, the next character in a diagonal is exactly columns + 1 indices away. • Refining the Loop: My first approach worked well, but I realized I could shave off execution time by adding an early exit. • The "Efficiency" Jump: By adding a simple check, if(j % column == column-1) break;—I stopped the inner loop from looking for diagonal neighbors that would logically fall outside the matrix boundaries. The Result: This small logic tweak dropped my runtime from 28ms down to 18ms, jumping from beating 56% to 97.63% of users. It’s a great reminder that even on "easier" problems, there’s always room to optimize. Seeing that performance graph move to the far left is the best kind of motivation. 🚀 #LeetCode #Java #StringManipulation #Algorithm #Optimization #DailyCode
Slanted Ciphertext Decoding & Loop Optimization
More Relevant Posts
-
#70DayStreak 🚀 27/04/26 — Optimized Sliding Window | Longest Substring Without Repeating Characters (LeetCode 3) Today I revisited a classic problem — Longest Substring Without Repeating Characters — and implemented a more optimized Sliding Window using HashMap. Previously, I used a HashSet approach where the window shrinks step-by-step. This time, I upgraded it with a "jumping window" technique, allowing direct pointer movement. 🔑 Key Optimization Insight Instead of removing characters one by one: • Store last seen index of each character • When duplicate appears → jump left pointer instantly • Avoid unnecessary iterations 👉 This reduces redundant work and improves efficiency significantly. ⚙️ Algorithm Highlights • Left pointer jumps using stored indices • Right pointer scans once • Continuous max window calculation 📊 Complexity • Time: O(n) • Space: O(min(m, n)) 📈 Performance • Runtime: 5ms (Beats 87.15%) • Memory: 45.67 MB (Beats 69.72%) 🔥 Consistency Metrics • 84 Active Days • 70-Day Streak 💡 Key Learning Switching from HashSet → HashMap transforms the approach from iterative shrinking to direct optimization. This is a small shift in thinking, but a big upgrade in performance. 📌 Even after 100+ problems, refinement and optimization still matter. #DSA #Java #LeetCode #SlidingWindow #HashMap #Algorithms #CodingJourney #ProblemSolving #Optimization #100DaysOfCode
To view or add a comment, sign in
-
-
✳️Day 35 of #100DaysOfCode✳️ 📌 Cracking the "Redundant Connection" Problem with DSU! 🛠️ My Approach: The DSU Strategy The Disjoint Set Union (or Union-Find) algorithm is perfect here because it allows us to track connected components efficiently as we iterate through the edges. ✨The Steps in my Code: 1️⃣Initialization: Created a parent array where every node is initially its own parent (representing n independent sets). 2️⃣Iterative Union: For every edge (u, v) in the input: Find the root (representative) of u. Find the root (representative) of v. Cycle Detection: * If find(u) == find(v), it means u and v are already part of the same connected component. Adding this edge would create a cycle. 🚩 Since the problem asks for the last edge that causes the cycle, I return this edge immediately. 3️⃣Union: If they are in different sets, I perform a union by setting the parent of one root to the other. 4️⃣Optimization: I used Path Compression in the find function to keep the tree flat, ensuring almost constant time complexity. 💡 When should you use DSU? 🔅DSU is a powerhouse for specific graph scenarios. Reach for it when: Cycle Detection: You need to check if adding an edge creates a cycle in an undirected graph. 🔅Connected Components: You need to count or manage groups of connected nodes dynamically. 🔅Minimum Spanning Trees: It’s the backbone of Kruskal’s Algorithm. Grid Problems: Identifying "islands" or connected regions in a 2D matrix. #DataStructures #Algorithms #LeetCode #Java #GraphTheory #CodingLife #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 75 — Slow & Fast Pointer (Happy Number Detection) Extending the slow‑fast pointer pattern beyond linked lists — today I applied it to a mathematical problem involving cycles. 📌 Problem Solved: - LeetCode 202 – Happy Number 🧠 Key Learnings: 1️⃣ The Problem in a Nutshell A number is happy if repeatedly replacing it with the sum of squares of its digits eventually reaches 1. If it enters a cycle that doesn’t include 1, it’s unhappy. 2️⃣ Why Slow‑Fast Pointer Works - The sequence of numbers (n → sum of squares of digits → ...) will eventually either reach 1 or enter a cycle. - This is exactly like detecting a cycle in a linked list — except the “next” is defined mathematically. - Slow moves one step: `slow = sq(slow)` - Fast moves two steps: `fast = sq(sq(fast))` - If they meet at a value other than 1 → cycle exists → unhappy number. - If fast reaches 1 → happy number. 3️⃣ The sq() Helper Computes sum of squares of digits. Clean and reusable. 4️⃣ Edge Cases - n = 1 → returns true immediately (loop condition `fast != 1` fails, returns true). - Numbers like 2, 3, 4 eventually cycle (4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4). 💡 Takeaway: The slow‑fast pointer pattern isn’t just for linked lists — it’s a general cycle detection tool that works for any sequence with a deterministic “next” step. Recognizing this abstraction is what makes a great problem solver. No guilt about past breaks — just one problem at a time, one pattern at a time. #DSA #SlowFastPointer #HappyNumber #CycleDetection #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
🚀 Just solved the Contains Duplicate problem with a fresh perspective! Instead of going with the traditional sorting + two pointer approach, I used the property of Set (uniqueness) to achieve an O(n) time complexity solution. 💡 Approach: - Traverse the array once - Use a HashSet to track elements - If an element already exists → duplicate found ⚡ Time Complexity: O(n) 📦 Space Complexity: O(n) 🔁 On the other hand, the sorting + two pointer approach gives: - Time: O(n log n) - Space: O(1) 👉 So it’s a classic trade-off: - Optimize time → use Set - Optimize space → use Sorting+two pointer Really enjoyed breaking down this problem and comparing approaches — small problems like this build strong intuition for bigger ones 💪 #DataStructures #Algorithms #LeetCode #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
Day 27 of my #30DayCodeChallenge: The Efficiency of Binary Exponentiation! The Problem: Pow(x, n). Implementing the power function to calculate x". While it sounds simple, the challenge lies in handling large exponents (up to 231 - 1) and negative powers without hitting time limits or overflow. The Logic: This problem is a classic example of Divide and Conquer optimized through Binary Exponentiation (also known as Exponentiation by Squaring): 1. Bitwise Breakdown: Instead of multiplying x by itself n times (O(n)), we decompose n into powers of 2. For example, x13 is x8. x4. x¹. This brings our complexity down to O(log n). 2. The Iterative Jump: In every iteration of the loop, we square the current base (x = x x). If the current bit of n is 1 (checked via n & 1), we multiply our result by the current base. 3. Handling the Edge Cases: * Negative Exponents: If n is negative, we calculate xI" and then take the reciprocal (1/result). Overflow: We use a long for n during calculation to avoid overflow when converting -2, 147, 483, 648 to a positive value. The Calculation: By halving the power at each step, we transform a task that could take 2 billion operations into one that takes just 31. One step closer to mastery. Onward to Day 28! #Java #Algorithms #DataStructures #BinaryExponentiation #ProblemSolving #150DaysOfCode #SoftwareEngineer
To view or add a comment, sign in
-
-
Worked on a challenging problem: “Subarrays with K Different Integers” Key takeaway: Instead of directly solving for exactly K distinct elements, I learned a smarter approach: 👉 count(at most K) − count(at most K−1) 🔹 Concepts I practiced: Sliding Window technique HashMap for frequency tracking Two-pointer approach 🔹 What stood out: The idea of counting all valid subarrays ending at each index using (r - l + 1) was really powerful. It completely changed how I think about subarray problems. Always learning, one problem at a time. #DataStructures #Algorithms #Java #LeetCode #SlidingWindow #LearningJourney #ProblemSolving
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
-
-
🚀 Cracked LeetCode 18 : 4Sum — From Naive to Optimal Approach Today I worked on the classic 4Sum problem — finding all unique quadruplets that sum to a target. 🔴 Naive Approach (Brute Force) Think of checking every possible quadruplet: Use 4 loops (i, j, k, l) Check if sum == target Store unique results using a set ⏱️ Time Complexity: O(n⁴) 👉 Works, but too slow for large inputs. 🟡 Better Approach (Hashing) Fix 2 elements Use a HashSet for remaining 2 elements (like 2Sum) ⏱️ Time Complexity: O(n³) 👉 Faster, but still not optimal. 🟢 Optimal Approach (Sorting + Two Pointers) 💡 Idea: Sort the array Fix first two numbers (i, j) Use two pointers (k, l) to find remaining pair ⏱️ Time Complexity: O(n³) But much faster in practice due to pruning & skipping duplicates. 💻 Pseudo Code (Easy to Understand): sort array for i from 0 to n-1: skip duplicates for i for j from i+1 to n-1: skip duplicates for j k = j + 1 l = n - 1 while k < l: sum = arr[i] + arr[j] + arr[k] + arr[l] if sum == target: store answer k++, l-- skip duplicates for k and l else if sum < target: k++ else: l-- 🔥 Key Interview Insight 👉 “Sort + Fix elements + Reduce to 2Sum using two pointers” #DataStructures #Algorithms #Java #LeetCode #CodingInterview #100DaysOfCode
To view or add a comment, sign in
-
🚀 Solved LeetCode 2515 – Shortest Distance to Target String in a Circular Array Today I tackled an interesting problem that highlights the importance of handling circular data structures efficiently. 🔍 Problem Insight: Given a circular array of words, a target string, and a starting index, the goal is to find the minimum number of steps required to reach the target by moving either left or right. 💡 Key Learnings: Circular arrays require thinking beyond linear traversal Always consider both directions (forward & backward) Optimizing distance using min(distance, n - distance) is the key trick Simple logic + correct observation = optimal solution ⚙️ Approach Used: Traverse the array to find all occurrences of the target Calculate distance from the starting index Take the minimum considering circular movement 📈 Complexity: Efficient O(n) solution with constant space 🔥 Takeaway: This problem reinforced how small tweaks (like circular behavior) can change the entire approach. A great example of combining logic + observation for clean and optimal solutions. #LeetCode #Algorithms #ProblemSolving #CodingJourney #Java #DataStructures #CompetitiveProgramming
To view or add a comment, sign in
-
-
🚀 Day 77 — Slow & Fast Pointer (Middle of the Linked List) Another day, another clean application of the slow‑fast pointer pattern — this time without cycle detection, just finding the midpoint efficiently. 📌 Problem Solved: - LeetCode 876 – Middle of the Linked List 🧠 Key Learnings: 1️⃣ The Problem Given the head of a singly linked list, return the middle node. If there are two middle nodes (even length), return the second one. 2️⃣ Why Slow‑Fast Pointer Works Here - `slow` moves 1 step at a time. - `fast` moves 2 steps at a time. - When `fast` reaches the end (or `fast.next == null`), `slow` is exactly at the middle. - For even length, `fast` ends at `null` → `slow` points to the second middle node (perfect for this problem’s requirement). 3️⃣ The Code (Simple & Elegant) while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; 4️⃣ Why Not Just Count Then Traverse? - Brute force: count nodes → traverse again → O(n) but two passes. - Slow‑fast pointer achieves the same in one pass with O(1) extra space. 💡 Takeaway: Slow‑fast pointer isn’t only for cycle detection. It’s a versatile tool for: - Finding middle (this problem) - Detecting cycles (LeetCode 141/142) - Finding duplicate numbers (LeetCode 287) - Happy number detection (LeetCode 202) Each problem adds a new dimension to understanding the same pattern. No guilt about past breaks — just showing up, solving, and growing. #DSA #SlowFastPointer #MiddleOfLinkedList #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
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