🚀 𝗗𝗮𝘆 12 𝗼𝗳 𝗖𝗼𝗻𝘀𝗶𝘀𝘁𝗲𝗻𝗰𝘆 — Solved “Valid Anagram” on LeetCode Today I worked on a classic string problem: Valid Anagram — a great question to strengthen understanding of frequency counting and optimized string handling. 🔍 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 Given two strings s and t, determine whether t is an anagram of s. 👉 Anagram means both strings contain the same characters with the same frequency. 🧠 𝗕𝗿𝘂𝘁𝗲 𝗙𝗼𝗿𝗰𝗲 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 Sort both strings Compare them ⏱ Time Complexity: O(n log n) 👉 Works fine but not optimal for interviews ⚡ 𝗢𝗽𝘁𝗶𝗺𝗶𝘇𝗲𝗱 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 (Used Today) Instead of sorting, I used frequency counting with arrays. ✅ 𝗦𝘁𝗲𝗽𝘀: If lengths are different → return false Create two arrays of size 26 (for lowercase letters) Count frequency of characters in both strings Compare both frequency arrays 💻 𝗖𝗼𝗱𝗲 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 Increment count for characters in s Increment count for characters in t Compare both arrays → if all values match → anagram ✅ 📌 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 s = "anagram" t = "nagaram" ✔ Same frequency → Valid Anagram ⏱ 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀 Time: O(n) Space: O(1) (constant size array) 💡 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 Always try to replace sorting with counting when dealing with characters Frequency array is a powerful optimization technique Writing clean and optimal code improves both performance and interview confidence Grateful for continuous learning and growth 🙏 Consistency is the real game changer 💯 #LeetCode #DSA #Java #ProblemSolving #CodingJourney #100DaysOfCode #TechLearning #SoftwareDevelopment
Valid Anagram Solution on LeetCode
More Relevant Posts
-
🚀 Day 33 of My DSA Journey – Reverse Vowels of a String (LeetCode) Today I worked on a really interesting problem: Reverse Vowels of a String — and learned how powerful the two-pointer approach can be. 🔍 Problem Understanding We are given a string, and we need to reverse only the vowels while keeping the rest of the characters in the same position. 👉 Example: Input: "hello" Output: "holle" 🐢 Brute Force Approach Extract all vowels into a separate list Reverse that list Traverse the string again and replace vowels one by one ⛔ Time Complexity: O(n) ⛔ Space Complexity: O(n) (extra storage used) ⚡ Optimized Approach (Two Pointer) Instead of extra space, I used two pointers (i, j): Steps: Initialize: i = 0 (start) j = n-1 (end) Move i forward until it finds a vowel Move j backward until it finds a vowel Swap both vowels Repeat until i < j 🧠 Example Walkthrough Input: "leetcode" i → 'e', j → 'e' → swap i → 'e', j → 'o' → swap Final Output: "leotcede" ⏱️ Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) ✅ (in-place) 💡 Key Learning Two-pointer approach is extremely useful for string manipulation problems Always try to reduce extra space usage Clean condition handling (like checking vowels) matters a lot in interviews 🙏 Thanks to LeetCode for such great problems that strengthen problem-solving skills. 📈 Consistency is the key — small steps daily lead to big results. #DSA #Java #LeetCode #ProblemSolving #CodingJourney #100DaysOfCode #InterviewPreparation #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 31 of #LeetCode Challenge 🔍 Problem: Decode the Slanted Ciphertext Today’s problem was all about understanding patterns and matrix traversal in a clever way! 💡 Key Idea: * The encoded string is formed by writing characters in a matrix row-wise * The trick is to read diagonally (↘️ direction) to decode the original message * No need to build a 2D matrix — we can directly calculate indices! 🧠 What I Learned: * How to convert 1D string into virtual 2D matrix * Diagonal traversal techniques * Importance of trimming trailing spaces in string problems ⚡️ Approach: * Calculate number of columns → cols = n / rows * Traverse diagonally from each column * Append characters using index formula i * cols + j * Remove extra spaces at the end 💻 Language: Java 🎯 Time Complexity: O(n) 📦 Space Complexity: O(n) Consistency is the key 🔑 — one problem at a time, getting better every day! #Day31 #LeetCode #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🧠 LeetCode POTD — The Biggest Hint Was Hidden in One Line 1855. Maximum Distance Between a Pair of Values Today's problem looked tricky at first considering the time complexity. We need to find indices (i, j) such that: 👉 i <= j 👉 nums1[i] <= nums2[j] And maximize: 👉 j - i ━━━━━━━━━━━━━━━━━━━ My first instinct? Try brute force combinations. Check many pairs. Maybe binary search. But I was missing the most important line in the question: Both arrays are non-increasing (sorted). That one detail changes everything. ━━━━━━━━━━━━━━━━━━━ 💡 Once I noticed that, the solution became a clean two-pointer approach. Start with: 👉 i = 0 in nums1 👉 j = 0 in nums2 Then: If nums1[i] <= nums2[j] 👉 This pair is valid 👉 Update answer with j - i 👉 Move j forward to try for a bigger distance Else: 👉 Current i is too large 👉 Move i forward Because arrays are sorted, once a pair fails, moving i is the only useful move. ━━━━━━━━━━━━━━━━━━━ 📌 What I liked about this problem: The challenge wasn't the coding. It was reading carefully enough to spot the property that unlocks the solution. ✅ Sometimes the answer is already in the problem statement. ✅ You just have to notice it. Curious — did anyone else miss the sorted hint at first? 👀 #LeetCode #TwoPointers #ProblemSolving #SoftwareEngineering #DSA #Java #c++ #SDE
To view or add a comment, sign in
-
-
LeetCode 41 – First Missing Positive. 🧩 When I first read this problem, I thought it would be messy. But once I found the pattern, it turned out to be surprisingly clean. The problem in simple terms: Find the smallest positive integer missing from an unsorted array. The real challenge: O(n) time and O(1) extra space. No sorting, no hash maps, no extra arrays. At first, that feels impossible. But here's the trick that clicked for me: The answer has to be between 1 and n+1 (where n = length of array). Why? Because in the best case, if the array contains 1,2,3,...,n, then the missing number is n+1. Otherwise, there's a gap somewhere between 1 and n. Once I realized that, the solution became straightforward: Place each number in its correct position (number x should be at index x-1) | After rearranging, scan to find the first spot where the number doesn't match the index + 1 That index + 1 is our answer What I liked about this problem: It teaches you to work within tight constraints. Instead of adding more memory, you use the array itself as your workspace. If you're preparing for coding interviews, this is one of those problems worth understanding deeply, not for memorizing the solution but for learning how to think under constraints. Have you run into a problem that looked impossible but turned out to have a simple pattern? Curious to hear your experience. #LeetCode #CodingInterview #ProblemSolving #Java #Algorithms
To view or add a comment, sign in
-
-
🚀 09/04/26 — Alternating Precision: Mastering String Merging Today I tackled Merge Strings Alternately (LeetCode 1768), focusing on efficient string construction and pointer management. This problem is an excellent exercise in handling sequences of different lengths using a unified traversal strategy. 🧵 Merge Strings Alternately Logic The goal is to merge two strings by adding letters in alternating order, starting with the first string. Any remaining letters from the longer string are appended to the end. StringBuilder Strategy: I used StringBuilder for the result to ensure efficient appends, avoiding the overhead of string concatenation in Java. The Interleaved Loop: I initialized two pointers, i and j, at 0. A single while loop runs as long as either string has remaining characters (i < word1.length() || j < word2.length()). Conditional Appending: Inside the loop, I check each pointer individually. If a pointer is still within its string's bounds, I append the character and increment that pointer. Automatic Handling: This structure naturally handles cases where one string is longer, as the conditions safely skip the shorter string once it is exhausted. Complexity Metrics: Time Complexity: O(a + b), where a and b are the lengths of word1 and word2, as every character is visited once. Space Complexity: O(a + b) to store the merged result in the StringBuilder. 📈 Consistency Report Today’s session further solidifies the pointer-based intuition I've been developing. The logic used here—managing multiple indices within a single loop—mirrors the "Two Sum" and "String Search" patterns I mastered earlier in the roadmap. Achieving a 95.66% beat rate proves that choosing the right tools, like StringBuilder, is just as important as the algorithm itself. My 1ms alternating merge implementation is attached below! 📄👇 #DSA #Java #LeetCode #StringManipulation #TwoPointers #Complexity #Consistency #LearningInPublic
To view or add a comment, sign in
-
-
**Day 110 of #365DaysOfLeetCode Challenge** Today’s problem: **Add Two Numbers II (LeetCode 445)** A very elegant **Linked List + Stack** problem. We are given two numbers stored in linked lists where the **most significant digit comes first**. Example: `7243 + 564 = 7807` Lists: `[7,2,4,3] + [5,6,4] = [7,8,0,7]` 💡 **Core Challenge:** Normally addition starts from the **last digit**… But linked lists are given from the **front**. So how do we add from right to left **without reversing the lists**? 📌 **Approach:** 1️⃣ Push digits of both linked lists into stacks 2️⃣ Pop from stacks → gives digits from right to left 3️⃣ Add with carry 4️⃣ Insert new node at the front of result list This preserves correct order naturally ⚡ **Time Complexity:** O(n + m) ⚡ **Space Complexity:** O(n + m) **What I learned today:** Stacks are incredibly useful when you need to process data in **reverse order**. 💭 **Key Takeaway:** If you can’t move backward easily: 👉 Use a stack 👉 Simulate reverse traversal 👉 Build result from front Clean solution. Smart idea. Great interview problem #LeetCode #DSA #LinkedList #Stack #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
Today I solved the problem: "Closest Target in Circular Array" 🔍 Problem Statement: Given an array of words and a starting index, find the shortest distance to a target word in a circular array. 💡 Key Idea: Since the array is circular, we must consider: ➡️ Direct distance ➡️ Circular distance 👉 Final distance = min(|i - startIndex|, n - |i - startIndex|) 🧑💻 My Optimized Java Solution: class Solution { public int closestTarget(String[] words, String target, int startIndex) { int n = words.length; int minDistance = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { if (words[i].equals(target)) { int dist = Math.abs(i - startIndex); int circularDist = Math.min(dist, n - dist); minDistance = Math.min(minDistance, circularDist); } } return minDistance == Integer.MAX_VALUE ? -1 : minDistance; } } 📈 What I Learned: How to handle circular array problems 🔄 Importance of optimizing brute-force solutions Writing clean and efficient code for interviews 🔥 Consistency is the key — one problem at a time! #LeetCode #Java #CodingJourney #ProblemSolving #100DaysOfCode #DSA
To view or add a comment, sign in
-
-
🚀 Day 79 of #LeetCode Journey Solved: Maximum Product Subarray 💡 At first, I implemented a brute-force approach (O(n²)) by checking all possible subarrays. It worked, but I knew it wasn’t efficient enough for interviews. Then I learned the optimized approach (O(n)) — and this problem became really interesting! 🔑 Key Insight: Because of negative numbers, the maximum product can suddenly become minimum and vice versa. 👉 So instead of tracking just the maximum, we track: Maximum product so far Minimum product so far This helps handle cases where: Negative × Negative = Positive And gives us the correct maximum product efficiently 📈 What I Learned: Not all problems are solved by simple iteration Tracking extra state can drastically improve performance Always think about edge cases like negatives & zeros 💻 Language: Java ⏱ Optimized Complexity: O(n) Consistency is the key 🔥 #Day79 #DSA #Java #CodingJourney #LeetCode #ProblemSolving
To view or add a comment, sign in
-
-
📅 Date: April 27, 2026 Day 6 of my LeetCode Journey 🚀 ✅ Problem Solved: 14. Longest Common Prefix 🧠 Approach & Smart Solution: To solve this problem, I used a highly efficient Horizontal Scanning technique. Instead of comparing characters index by index across all strings, I assumed the very first string was the common prefix. Then, I iteratively compared it with the next strings, shaving off characters from the end until a match was found. By leveraging Java's built-in startsWith() method, the logic is kept clean and readable! • Pseudo-code: Assume the first string in the array is the initial 'prefix'. Loop through the rest of the strings in the array: While the current string does not start with the 'prefix': Shorten the 'prefix' by removing its last character. If the 'prefix' becomes completely empty, return "" (no common prefix exists). Return the final 'prefix' after checking all strings. This step-by-step reduction ensures we only do as much work as absolutely necessary. ⏱️ Time Complexity: O(S) (where S is the sum of all characters in all strings) 📦 Space Complexity: O(1) (Only modifying the prefix string, no extra arrays used) 📊 Progress Update: • Streak: 5 Days 🔥 • Difficulty: Easy • Pattern: String / Horizontal Scanning 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Smartly utilizing built-in string methods like startsWith and substring can drastically reduce code complexity! 💡 #LeetCode #DSA #Strings #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
More from this author
Explore related topics
- Leetcode Problem Solving Strategies
- LeetCode Array Problem Solving Techniques
- Approaches to Array Problem Solving for Coding Interviews
- How to Use Arrays in Software Development
- Why Use Coding Platforms Like LeetCode for Job Prep
- Tips for Coding Interview Preparation
- Maintaining Consistent Coding Principles
- Common Algorithms for Coding Interviews
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