🚀 Day 2 of My Coding Practice! Solved another problem today on LeetCode – 1071. Greatest Common Divisor of String Problem Statement: Given two strings str1 and str2, return the largest string that divides both strings. Key Idea: If a string divides both strings, then: (str1 + str2) must be equal to (str2 + str1). Then the answer length will be: GCD(length of str1, length of str2) Algorithm Steps Input: String str1, String str2 Output: Largest common divisor string Algorithm: Check if (str1 + str2) equals (str2 + str1). If not equal → return empty string. Find gcd of lengths of str1 and str2. Return substring of str1 from 0 to gcd length. Example Walkthrough Input: str1 = "ABCABC" str2 = "ABC" Process: "ABCABCABC" == "ABCABCABC" ✔ GCD(6, 3) = 3 Output: "ABC" Pseudocode function gcdOfStrings(str1, str2): if (str1 + str2) ≠ (str2 + str1): return "" len1 = length of str1 len2 = length of str2 gcdLength = gcd(len1, len2) return substring of str1 from 0 to gcdLength 📌 Concepts Practiced: ✔ String concatenation logic ✔ Mathematical GCD ✔ Problem-solving approach Consistency over intensity 💪 #LeetCode #Java #ProblemSolving #Day2 #100DaysOfCode #BTech
LeetCode Solution: GCD of String Problem
More Relevant Posts
-
🚀 Daily LeetCode Challenge – Day 37 Today’s problem was Find All Possible Stable Binary Arrays I. Problem: We are given three integers zero, one, and limit. We need to count the number of stable binary arrays such that: The array contains exactly zero number of 0s. The array contains exactly one number of 1s. Any subarray with size greater than limit must contain both 0 and 1. In simpler terms, we cannot place more than limit consecutive 0s or 1s, otherwise the array becomes unstable. The brute force that came to mind: Generate all possible arrays using the given number of 0s and 1s and then check if they satisfy the limit condition. But this approach quickly becomes inefficient because the number of combinations grows rapidly. 💡 Better Idea – Dynamic Programming with Memoization First, we focus on the limit. The limit tells us the maximum number of identical elements that can appear consecutively. For example, if limit = 2, then sequences like [0,0,0] or [1,1,1] are not allowed because they contain more than two identical elements in a row, which would make the array unstable. To construct valid arrays, we add elements in blocks: ->If the last placed element was 1, the next block must contain 0s. ->If the last placed element was 0, the next block must contain 1s. ->The size of each block can range from 1 to min(remaining elements, limit). This ensures that: we never exceed the number of remaining 0s or 1s we never violate the limit constraint. We recursively explore all valid possibilities while keeping track of: ->remaining 0s ->remaining 1s ->the last placed element. To avoid recomputation, we store previously computed results in a DP table. ⚡ Time Complexity: O(zero × one × limit) ⚡ Space Complexity: O(zero × one) 🔍 Key Insight: Instead of generating all binary arrays, we construct them step by step while respecting the limit constraint and store intermediate results, which turns an exponential brute force solution into an efficient dynamic programming approach. #LeetCode #DailyCodingChallenge #Java #DynamicProgramming #Algorithms #ProblemSolving #CodingInterview
To view or add a comment, sign in
-
-
🚀 Day 4 – LeetCode Practice Today, I solved the 4Sum problem on LeetCode: 🎯 Difficulty: Medium 💻 Language Used: Java 💡 Approach: • Given an integer array nums and a target value, the goal was to find all unique quadruplets that sum up to the target. • I started by sorting the array to simplify searching and handling duplicates. • Used a nested loop structure with a two-pointer technique for the inner pair search: – The first two pointers fixes the first two elements, and the two pointers inside find matching pairs. • Skipped duplicates carefully to ensure unique quadruplets in the final list. ⏱ Complexity: • Time Complexity: O(n³) • Space Complexity: O(1) (excluding result storage) 📚 Key Takeaway: This problem strengthened my understanding of multi-pointer techniques, careful duplicate handling, and how sorting can significantly simplify complex combination searches. Consistent problem-solving practice continues to build my algorithmic intuition and coding confidence. 💪 #LeetCode #Java #DSA #TwoPointers #Sorting #ProblemSolving #Algorithms #100DaysOfCode #SoftwareDeveloper
To view or add a comment, sign in
-
-
🚀 #LeetCode 1404 — Number of Steps to Reduce a Number in Binary Representation to One | #Day150 of #365DaysOfCode Today’s problem looked innocent… until constraints said binary string length up to 500. That’s where brute force officially gets laid off from the company payroll. 🧠 Core Insight You are not allowed to convert the binary string into an integer. Why? Because the value can exceed 2^500 → way beyond long, BigInteger becomes slow, and simulation becomes the real game. This problem is actually about carry propagation, not arithmetic. ❌ Naive Thinking (What most people do) Convert binary → decimal Repeatedly divide by 2 / add 1 Count steps This fails: Overflow Time complexity explosion Wrong abstraction 🧩 Correct Model Operate directly on bits. Rules: Even → divide by 2 → shift right Odd → add 1 → causes carry chain So we simulate the effect of operations, not the number. ⚡ Optimal Greedy Approach (O(n)) We track a carry. For each bit from right to left: BitCarrySteps001102012111 Final answer = steps + carry 💻 Java Solution class Solution { public int numSteps(String s) { int steps = 0; int carry = 0; for(int i = s.length()-1; i > 0; i--) { int bit = s.charAt(i) - '0'; if(bit + carry == 1){ steps += 2; carry = 1; } else { steps += 1; } } return steps + carry; } } ⏱ Complexity Time: O(n) Space: O(1) 📊 Result Runtime: 0 ms (100%) Memory: 42.55 MB (93.81%) 🎯 Takeaway When constraints grow → switch from value thinking to representation thinking. You’re not solving math. You’re simulating hardware logic. #leetcode #leetcode1404 #dsa #algorithms #datastructures #coding #codinginterview #programming #softwareengineering #bitmanipulation #greedy #computerscience #competitiveprogramming #interviewprep #faang #faangprep #tech #developer #codinglife #100daysofcode #java #python #problemSolving #career #learning #students #engineering #placementpreparation #techcommunity #codingjourney #developerlife
To view or add a comment, sign in
-
-
🚀 Day 132 of #1000DaysOfCode LeetCode Daily Challenge — Day 56 56 days. Zero breaks. Steady execution. Today’s problem revolved around custom sorting logic using bit manipulation — ordering integers based on the number of set bits with a well-structured comparator. Key takeaways: • Strengthened understanding of custom comparator design • Applied bitCount effectively within sorting logic • Reinforced hybrid thinking: bit manipulation + sorting • Improved clarity in writing clean and optimized Java solutions ✔️ Accepted solution 🔁 56-Day Coding Streak At this stage, pattern recognition is becoming faster. Less hesitation. More structure. Cleaner implementation. Onward to 60 days. 🚀 #LeetCode #Consistency #Algorithms #DataStructures #Java #BitManipulation #Sorting #ProblemSolving #SoftwareEngineering #CodingJourney
To view or add a comment, sign in
-
-
🚀 Today’s LeetCode Problem — Sort Integers by Number of 1 Bits Let’s solve today’s LC in story mode 🎭 Imagine numbers are contestants in a Binary Costume Contest. Today’s contestants: 👉 [5, 3, 7] But this contest has a twist 👇 👨⚖️ The judge doesn’t care about the number itself first. He cares about… 🎈 How many 1s are in their binary costume 🎭 What Are They Wearing? 🔹 5 → 101 → 🎈🎈 (2 ones) 🔹 3 → 011 → 🎈🎈 (2 ones) 🔹 7 → 111 → 🎈🎈🎈 (3 ones) 🏆 Judge’s Rules 1️⃣ Fewer 1s → Higher priority 2️⃣ Same number of 1s → Smaller number wins 👉 Step 1: 3 & 5 → 2 ones 7 → 3 ones So 7 goes last. 👉 Step 2: Tie between 3 and 5 Smaller number first → 3 before 5 ✅ Final Answer: [3, 5, 7] 💡 How I Solved It I implemented this using: 🔹 Brian Kernighan’s Algorithm for efficient bit counting 🔹 TreeMap to maintain sorted order by bit count + value 🔹 Also compared with built-in bitCount() + custom comparator sorting This ensures: ✔ Efficient bit counting ✔ Clean tie-breaking ✔ Optimal sorting logic If you’re interested, I’ve pushed the complete solution (Kernighan + TreeMap + built-in approach) : https://lnkd.in/gV9HZ9w4 👨💻 Would love feedback from fellow developers 🙌 #LeetCode #DSA #Java #ProblemSolving #CodingJourney #100DaysOfCode #Tech #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 29/60 — LeetCode Discipline Problem Solved: Longest Common Prefix Difficulty: Easy Today’s problem focused on identifying the longest common starting pattern across multiple strings — a classic exercise in string comparison and iteration. The approach involved checking characters position by position across all strings until a mismatch is found. This reinforces how simple iterative logic can elegantly solve problems involving multiple inputs. It’s a reminder that sometimes, clarity in approach matters more than complexity in code. 💡 Focus Areas: • Strengthened string traversal techniques • Practiced comparing multiple inputs efficiently • Improved understanding of edge cases (empty strings, mismatch handling) • Reinforced early stopping conditions for optimization • Focused on clean and readable logic ⚡ Performance Highlight: Achieved efficient runtime with minimal overhead. Finding common ground across multiple inputs is not just a coding skill — it’s a pattern recognition mindset. #LeetCode #60DaysOfCode #100DaysOfCode #DSA #Strings #Algorithms #ProblemSolving #CodingJourney #SoftwareEngineering #Java #Developers #Consistency #TechGrowth #LearnToCode
To view or add a comment, sign in
-
-
Two Pointers pattern — done. Here's what the last few days actually taught me. 🧵 Three Sum is Two Sum with a loop around it. First time I saw Three Sum — find all triplets that sum to zero — I thought it was a completely different problem. Turns out it isn't. Fix one element i. Now you just need two numbers from the rest of the array that sum to -arr[i]. That's Two Sum. Which is Two Pointers. Which you already know. Three Sum = loop + Two Sum. Four Sum = loop + Three Sum. The pattern scales. The core never changes. --- Dutch National Flag — the hardest-looking problem with the simplest explanation. Sort an array of only 0s, 1s, and 2s. In-place. No sort(). Single pass. The instructor explained it as a teacher sorting students — toppers (0) to the front, failures (2) to the back, average (1) stays in the middle. Three pointers: low, mid, high. Mid scans the unsorted zone and decides where each element belongs. O(n) time. O(1) space. One pass. The analogy made the algorithm stick instantly. --- The real output of this pattern: a decision framework. After every question, the same signals kept showing up: → Array or linked list problem → Sorted, or sorting helps → Merge / rearrange / remove duplicates in-place → Find a pair, triplet, or quadruplet Match two or more of these → Two Pointers is almost certainly the answer. Not intuition. A repeatable framework. Next: Sliding Window. Which, turns out, is just a specific type of Two Pointers. 💻 #DSA #TwoPointers #LeetCode #Java #CodingJourney #DSAPatterns #PadhoWithPratyush Pratyush Narain
To view or add a comment, sign in
-
🚀 Day 5/50 – LeetCode Challenge 🧩 Length of Last Word Today’s problem focused on string handling and edge case management. 📌 Problem Summary: Given a string consisting of words and spaces, return the length of the last word in the string. A word is defined as a sequence of non-space characters. 🔍 Approach Used: Ignored trailing spaces Traversed the string from the end Counted characters until a space was found This approach avoids unnecessary splitting and improves efficiency. ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) 💡 Key Learning: ✔️ Efficient string traversal ✔️ Handling trailing spaces ✔️ Edge case management ✔️ Avoiding extra memory usage A simple problem that highlights the importance of clean logic and careful handling of input. Consistency builds mastery 💪 🔗 Problem Link: https://lnkd.in/ghA_rYmP #50DaysOfLeetCode #LeetCode #DSA #Java #Strings #ProblemSolving #CodingJourney #FutureAIEngineer #Consistency
To view or add a comment, sign in
-
-
🚀 Day 30/60 — LeetCode Discipline Problem Solved: 3Sum Closest Difficulty: Medium Today’s problem pushed beyond exact answers and focused on finding the closest possible sum to a given target — a subtle yet powerful variation of the classic 3Sum problem. By sorting the array and using a two-pointer approach, the solution efficiently explores combinations while continuously updating the closest result. This problem highlights how small modifications in logic can significantly change the nature of a problem — from exact matching to optimal approximation. 💡 Focus Areas: • Strengthened two-pointer technique • Practiced working with sorted arrays • Improved handling of optimization conditions • Learned to track and update closest values dynamically • Reinforced problem-solving under constraints ⚡ Performance Highlight: Achieved efficient runtime with optimized traversal. Not every problem asks for perfection — sometimes, the goal is to get as close as possible. #LeetCode #60DaysOfCode #100DaysOfCode #DSA #TwoPointers #Algorithms #ProblemSolving #CodingJourney #SoftwareEngineering #Java #Developers #Consistency #TechGrowth #LearnToCode
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
great job