Sometimes a brute force approach is more than enough before jumping to complex optimizations. 🚀 While solving LeetCode 3713 – Longest Balanced Substring, I followed a straightforward brute-force strategy that worked effectively within constraints. 🔍 Approach: The idea is to check every possible substring and verify whether it is balanced. A substring is considered balanced if all characters present in it appear the same number of times. 1. Iterate through every possible starting index i. 2. For each start, extend the substring with index j. 3. Maintain a frequency array of size 26 to track occurrences of characters. 4. After each extension, check whether all non-zero frequencies are equal. 5. If the substring is balanced, update the maximum length. (The helper function verifies the balance condition by ensuring all characters that appear in the substring have the same frequency.) ⏱ Time Complexity: >Outer loop for start index → O(n) >Inner loop for end index → O(n) >Balance check over 26 characters → O(26) ≈ O(1) >Overall Time Complexity: O(n²) 💾 Space Complexity: >Frequency array of size 26 → O(1) (constant space) ✨ Sometimes the simplest idea—checking all possibilities carefully—can solve the problem efficiently without overcomplicating the solution. #LeetCode #ProblemSolving #DataStructures #Algorithms #Java #CodingJourney
Balanced Substring Solution for LeetCode 3713
More Relevant Posts
-
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
To view or add a comment, sign in
-
-
🚀 Day 546 of #750DaysOfCode🚀 🔥 Solved: Check if Strings Can be Made Equal With Operations I (LeetCode Easy) 💡 Problem Insight We are allowed to swap characters at indices where: 👉 j - i = 2 This means: Index 0 ↔ 2 (even positions) Index 1 ↔ 3 (odd positions) 🚫 But we cannot mix even and odd indices 🧠 Key Observation The string is divided into 2 independent groups: Even indices → (0, 2) Odd indices → (1, 3) 👉 We can rearrange within each group freely 👉 So both groups must match between s1 and s2 ⚡ Approach Extract characters: Even indices from both strings Odd indices from both strings Sort both groups Compare: Even parts must match Odd parts must match 📈 Complexity Time: O(1) Space: O(1) 💬 Key Takeaway Sometimes problems look like string manipulation, but the real trick is: 👉 Understanding constraints → grouping → independent transformations 🔁 Consistency check ✔️ Another day, another step forward 🚀 #LeetCode #DataStructures #Algorithms #Java #CodingChallenge #ProblemSolving #100DaysOfCode #Consistency
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
-
-
💭 Today’s lesson: Not every problem needs complex logic. Sometimes, it’s about seeing the pattern clearly. I was solving today’s LeetCode problem: 👉 Check if two strings can be made equal with operations At first glance, it felt like a typical string manipulation problem. But the constraint made it interesting: You can only swap characters at positions with the same parity (even ↔ even, odd ↔ odd). Initially, I started overthinking: ->“Do I need to simulate swaps?” ->“Is this a graph / permutation problem?” But then I paused and asked: 👉 What actually changes after unlimited valid operations? 💡 That’s when the key insight clicked: ->Characters at even indices can only rearrange among even positions ->Characters at odd indices can only rearrange among odd positions So instead of simulating swaps, we just need to check: ✔ Do both strings have the same frequency of characters at even positions? ✔ And the same for odd positions? That reduces the problem to a simple frequency comparison — much cleaner and efficient. Implemented it using two frequency arrays (even & odd), and it worked smoothly ✅ 🔍 Big takeaway: Before jumping into implementation, always ask: 👉 What constraints actually limit or define the problem? Sometimes, the best solution is not more code — but better observation. #DataStructures #Algorithms #LeetCode #ProblemSolving #Java #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
🚀 Day 46 of #100DaysOfCode Solved 719. Find K-th Smallest Pair Distance on LeetCode 📏 🧠 Key Insight: We need to find the k-th smallest absolute difference among all possible pairs in the array. Brute force (generating all pairs) would be O(n²) → not efficient. Instead, we use Binary Search on Answer + Two Pointers. ⚙️ Approach: 1️⃣ Sort the array 2️⃣ Define search space: 🔹left = 0 (minimum distance) 🔹right = max(nums) - min(nums) 3️⃣ Apply Binary Search: 🔹For a given mid, count how many pairs have distance ≤ mid 4️⃣ Counting pairs efficiently: 🔹Use two pointers 🔹For each i, move j while nums[j] - nums[i] ≤ mid 🔹Add (j - i - 1) to count 5️⃣ If count ≥ k → try smaller distance 6️⃣ Else → increase distance 🎯 Final answer = smallest distance satisfying the condition ⏱️ Time Complexity: O(n log n + n log D) 🔹Sorting + Binary Search with linear check 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #BinarySearch #TwoPointers #Algorithms #Java #InterviewPrep #CodingJourney
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 70 - LeetCode Journey Solved LeetCode 88: Merge Sorted Array (Easy) today — a classic problem that focuses on array manipulation and the two-pointer technique. The challenge is to merge two sorted arrays into one sorted array without using extra space, by modifying nums1 in-place. 💡 Core Idea: Instead of merging from the beginning, we start from the end of the arrays. Why? Because nums1 already has extra space at the end to accommodate elements from nums2. We use three pointers: • i → last valid element in nums1 • j → last element in nums2 • k → last position of merged array At each step, we place the larger element at position k, ensuring the array remains sorted. ⚡ Key Learning Points: • Using the two-pointer technique from the end • Performing in-place array merging • Maintaining O(m + n) time complexity • Avoiding unnecessary extra space This problem is a great reminder that sometimes changing the direction of traversal makes the solution much simpler. ✅ Better understanding of array manipulation ✅ Stronger grasp of two-pointer techniques ✅ Improved problem-solving efficiency Small problems like this build strong fundamentals for bigger challenges 🚀 #LeetCode #DSA #Java #TwoPointers #Arrays #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
🚀 Day 25 of my #100DaysOfCode Journey Today, I solved the LeetCode problem Valid Perfect Square. Problem Insight: Given a positive integer, the task is to determine whether it is a perfect square without using built-in functions like sqrt(). Approach: Used Binary Search to efficiently find whether a number has an integer square root. Initialized search range from 0 to num Calculated mid and checked mid * mid If equal → return true If square is smaller → move right (low = mid + 1) If square is larger → move left (high = mid - 1) Used long for multiplication to avoid overflow issues. Time Complexity: O(log n) — efficient binary search approach Takeaway: Binary Search is not just for arrays — it can be applied to mathematical problems to optimize performance and avoid brute force. #DSA #Java #LeetCode #CodingJourney #100DaysOfCode #BinarySearch
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 27 Problem: 3786. Cyclic Shifts of a Matrix Topic: Array, Matrix, Math, Simulation 📌 Quick Problem Sense: You're given an m × n matrix and an integer k. Every step: even-indexed rows shift left, odd-indexed rows shift right — repeated k times. Return true if the matrix after k steps is identical to the original. The catch? k can be huge — so simulating step by step is a dead end. 🚫 🧠 Approach (Simple Thinking): 🔹 A row of length n always returns to original after n shifts — but it might return sooner! 🔹 The minimum cyclic period of a row = the smallest divisor d of n such that the row is just a block of size d repeated 🔹 Check it: row[j] == row[j % d] for all j — if true, d is the period! 🔹 Direction (left vs right) doesn't affect the period — both complete their cycle in the same number of steps 🔹 The matrix restores to original iff k % period == 0 for every row 🔹 Get all divisors of n once in O(√n), check each row against them — no simulation needed! 🎯 ⏱️ Time Complexity: Divisors of n → O(√n) Per row period check → O(d(n) × n) All rows → O(m × d(n) × n) Blazing fast — no k-step simulation ever needed! 📦 Space Complexity: Just a divisors list → O(√n) Zero extra matrix copies or simulation buffers! I wrote a full breakdown with dry run, real-life analogy, and step-by-step code walkthrough here 👇 https://lnkd.in/gbqN_Y7a If you solved it using the KMP failure function to find the string period in O(n), I'd love to see that approach, drop it in the comments 💬 See you in the next problem 👋 #LeetCode #DSA #CodingChallenge #Java #ProblemSolving
To view or add a comment, sign in
-
-
🚀 LeetCode Problem || Rotate Array Problem Today I worked on the classic Rotate Array problem and explored 3 different approaches to solve it: Approach 1: Brute Force Rotate the array one step at a time (k times). Time Complexity: O(n * k) Approach 2: Using Extra Space Use another array to place elements in rotated positions. Time Complexity: O(n) Space Complexity: O(n) Approach 3: Optimized (Reversal Algorithm) ✅ This is the approach I implemented: ✔️ Reverse the entire array ✔️ Reverse first k elements ✔️ Reverse remaining elements ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) ✨ Learning takeaway: This is a basic problem, but it really helps in building strong problem-solving thinking and understanding optimization techniques. #DataStructures #Java #Coding #ProblemSolving #LeetCode #LearningJourney
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