👉 Given a string of uppercase English letters, find the number of pairs (i, j) such that: A[i] = 'A' A[j] = 'G' i < j In simple terms, count how many times 'A' appears before 'G' in the string. 🔘 Brute Force Approach (O(n²)) The most straightforward way is to check every pair: for(int i = 0; i < n; i++) { if(arr[i] == 'A') { for(int j = i + 1; j < n; j++) { if(arr[j] == 'G') { ans++; } } } } ---------------------------------------------------------- 🔘 Optimized Approach (O(n)) Instead of checking every pair, we can: Keep track of how many 'A' we have seen so far. Every time we encounter a 'G', add the count of previous 'A' to the answer. int countA = 0; for(int i = 0; i < n; i++) { if(arr[i] == 'A') { countA++; } else if(arr[i] == 'G') { ans += countA; } } #Java #DSA #Algorithms #ProblemSolving #CodingInterview #InterviewPreparation #DataStructures #TimeComplexity #Optimization #SoftwareEngineering #Developers #TechCareers #CodingJourney #LearnToCode #Programming
Counting 'A' before 'G' in a String
More Relevant Posts
-
Day 74/365 – Remove Duplicate Letters Problem: Given a string s, remove duplicate letters so that each letter appears once and the result is the smallest lexicographical order possible. Example: "bcabc" → "abc" "cbacdcbc" → "acdb" 💡 Key Idea Use a Monotonic Stack to maintain characters in lexicographically smallest order. We also track: • Last occurrence of each character • Whether a character is already used in the result 🧠 Approach 1️⃣ Record the last index of each character. 2️⃣ Traverse the string. 3️⃣ Skip characters already included. 4️⃣ While stack top is bigger than current character and it appears later again, remove it to get a smaller result. 5️⃣ Push current character into the stack. 📦 Key Logic while(!stack.isEmpty() && stack.peek() > c && lastIndex[stack.peek() - 'a'] > i) { visited[stack.pop() - 'a'] = false; } This ensures: Lexicographically smallest result Each character appears only once 📊 Complexity ⏱ Time: O(n) 📦 Space: O(1) (since only 26 letters) ✨ Key Learning This is a classic Monotonic Stack + Greedy problem. Pattern to remember: 👉 Remove previous larger elements if they appear again later. This pattern appears in problems like: Smallest Subsequence Remove K Digits Monotonic stack optimization problems #Day74 #365DaysOfCode #LeetCode #MonotonicStack #GreedyAlgorithm #DataStructures #Algorithms #Java #DSA #CodingInterview
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟲𝟲/𝟭𝟬𝟬 — 𝗘𝘃𝗮𝗹𝘂𝗮𝘁𝗲 𝗥𝗲𝘃𝗲𝗿𝘀𝗲 𝗣𝗼𝗹𝗶𝘀𝗵 𝗡𝗼𝘁𝗮𝘁𝗶𝗼𝗻 Day 66. Two-thirds done. Today's problem? The reason calculators exist. 𝗧𝗼𝗱𝗮𝘆'𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: ✅ #𝟭𝟱𝟬: Evaluate Reverse Polish Notation (Medium) 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: Evaluate expressions in Reverse Polish Notation (RPN). Numbers come first, operators after. Example: ["2","1","+","3","*"] → ((2+1)*3) = 9 No parentheses needed. No order of operations confusion. Just read left to right. 𝗧𝗵𝗲 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Stack. When you see a number, push it. When you see an operator, pop two numbers, apply the operation, push the result. The last number standing? That's your answer. Used ArrayList as a stack for cleaner syntax with removeLast(). Same LIFO behavior. 𝗪𝗵𝘆 𝗜𝘁 𝗠𝗮𝘁𝘁𝗲𝗿𝘀: This is how calculators and compilers evaluate expressions internally. RPN eliminates ambiguity. "3 + 4 * 5" needs rules. "3 4 5 * +" doesn't. Understanding this makes you understand how expression parsing works. 𝗖𝗼𝗱𝗲: https://lnkd.in/gXwcqVdP 𝗗𝗮𝘆 𝟲𝟲/𝟭𝟬𝟬 ✅ 𝟲𝟲 𝗱𝗼𝘄𝗻. 𝟯𝟰 𝘁𝗼 𝗴𝗼. #100DaysOfCode #LeetCode #Stack #RPN #Algorithms #ExpressionEvaluation #CodingInterview #Programming #Java #MediumLevel #CompilerDesign
To view or add a comment, sign in
-
Day 44 of My DSA Journey 🚀 | Problem: Reverse a String 🧠 Problem Summary: Given a string, reverse the characters of the string. 💡 Key Concepts: • Two-pointer technique • Character array conversion • In-place swapping • String reconstruction 🧠 Approach: I used the two-pointer technique to reverse the string. Step-by-step: • Convert the string into a character array using toCharArray(). • Initialize two pointers: → left at the beginning of the array → right at the end of the array. • Swap characters at left and right. • Move left forward and right backward. • Continue until both pointers meet. Finally, convert the modified character array back into a string. 📈 Time Complexity: O(n) — each character is visited once 📉 Space Complexity: O(n) — character array created from the string 🧪 Test Case: Input: "I love Java" Output: "avaJ evol I" 🔧 Practical Usage / Why This Matters: • Text formatting in applications • Reversing data in string manipulation tasks • Processing palindromic transformations • Preprocessing strings in compilers or parsers 🌱 What I Learned Today: I reinforced how two-pointer swapping is a simple and efficient way to manipulate string data. 💬 How would you solve this problem differently? Share your approach! 🙌 If you're preparing for placements, let’s connect and grow together! #dsa #string #javaprogramming #coding #problemSolving #datastructures #algorithms #softwareengineering #placements #developerjourney
To view or add a comment, sign in
-
-
𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐇𝐚𝐫𝐝 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝: 𝐅𝐢𝐧𝐝 𝐭𝐡𝐞 𝐒𝐭𝐫𝐢𝐧𝐠 𝐰𝐢𝐭𝐡 𝐋𝐂𝐏 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 𝐋𝐢𝐧𝐤 :https://lnkd.in/gPQ5WExk 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧 𝐋𝐢𝐧𝐤 : https://lnkd.in/gYpvYnaW Today I worked on an interesting 𝐡𝐚𝐫𝐝 𝐩𝐫𝐨𝐛𝐥𝐞𝐦: 𝐅𝐢𝐧𝐝 𝐭𝐡𝐞 𝐒𝐭𝐫𝐢𝐧𝐠 𝐰𝐢𝐭𝐡 𝐋𝐂𝐏. The problem provides an 𝐋𝐂𝐏 (𝐋𝐨𝐧𝐠𝐞𝐬𝐭 𝐂𝐨𝐦𝐦𝐨𝐧 𝐏𝐫𝐞𝐟𝐢𝐱) 𝐦𝐚𝐭𝐫𝐢𝐱 and asks us to construct the lexicographically smallest string that satisfies this matrix. 𝐊𝐞𝐲 𝐈𝐝𝐞𝐚 Instead of constructing substrings directly, the approach is: 1️⃣ Start assigning characters from 'a' onward. 2️⃣ If lcp[i][j] > 0, it means the substrings starting at i and j share the same first character. 3️⃣ Propagate the same character across positions where the LCP value indicates a match. 4️⃣ Finally, validate the entire LCP matrix using the rule: lcp[i][j] = (word[i] == word[j]) ? 1 + lcp[i+1][j+1] : 0 If any condition fails, no valid string exists. 𝐖𝐡𝐚𝐭 𝐈 𝐥𝐞𝐚𝐫𝐧𝐞𝐝 • How LCP matrices represent relationships between substrings • Constructing strings using greedy character assignment • Validating constraints using dynamic programming relations • Importance of verifying generated structures against given matrices Problems like this really sharpen string manipulation + matrix reasoning skills. Always fun pushing through Hard-level challenges! #LeetCode #DataStructures #Algorithms #CodingPractice #Java #ProblemSolving
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge Today’s problem was Find Unique Binary String. Problem: We are given n unique binary strings of length n. The task is to return any binary string of length n that does not exist in the given array. At first glance, brute force might come to mind: Generate all 2^n binary strings and check which one is missing. But that’s inefficient. 💡 Better Idea – Diagonal Trick (Inspired by Cantor’s Diagonal Argument) Instead of checking all possibilities, we construct a new string by flipping the i-th bit of the i-th string. The new string will differ from every string in the array at least at one position. Therefore, it cannot match any existing string. ⚡ Time Complexity: O(n) ⚡Space Complexity: O(n) 🔍 Key Insight: By flipping the diagonal bits, we guarantee the generated binary string is different from every given string. Problems like this remind me that a simple mathematical idea can lead to a really elegant algorithm. #LeetCode #DailyCodingChallenge #Java #Algorithms #DataStructures #ProblemSolving #CodingInterview
To view or add a comment, sign in
-
-
𝗩𝗶𝘀𝘂𝗮𝗹𝗶𝘀𝗶𝗻𝗴 𝗢(𝗹𝗼𝗴 𝗡) 𝗥𝗮𝗻𝗴𝗲 𝗨𝗽𝗱𝗮𝘁𝗲𝘀: 𝗟𝗮𝘇𝘆 𝗣𝗿𝗼𝗽𝗮𝗴𝗮𝘁𝗶𝗼𝗻 🧠 Standard Segment Trees are powerful for Range Queries, but they hit a bottleneck with Range Updates. If you update a range [L, R], a standard tree forces you to update every leaf node, degrading performance to O(N). Enter 𝗟𝗮𝘇𝘆 𝗣𝗿𝗼𝗽𝗮𝗴𝗮𝘁𝗶𝗼𝗻. I visualised this using the following example: 🔹 𝗔𝗿𝗿𝗮𝘆: {2, 3, 1, 9, 3, 2, 5, 8, 7, 2} 🔹 𝗨𝗽𝗱𝗮𝘁𝗲 𝗤𝘂𝗲𝗿𝘆: L=3, R=9, Val += 5 𝗧𝗵𝗲 𝗠𝗲𝗰𝗵𝗮𝗻𝗶𝗰𝘀 (𝗦𝗲𝗲 𝗜𝗺𝗮𝗴𝗲𝘀): When the update function runs, it traverses the tree. Instead of going all the way down to the leaf nodes 9, 3, 2, 5, 8, 7, 2: 1. 𝗣𝗮𝗿𝘁𝗶𝗮𝗹 𝗢𝘃𝗲𝗿𝗹𝗮𝗽: For nodes that only partially cover the range [3, 9], the algorithm pushes any existing lazy values down (push) and recurses. 2. 𝗧𝗼𝘁𝗮𝗹 𝗢𝘃𝗲𝗿𝗹𝗮𝗽: Once a node is fully contained within [3, 9], we stop!• We update the current node's sum. • We add 5 to its lazy tag. • We 𝗿𝗲𝘁𝘂𝗿𝗻 immediately without touching the children. The "pending" updates are only pushed down to the children in future queries when absolutely necessary. This guarantees that both Point Queries and Range Updates remain 𝗢(𝗹𝗼𝗴 𝗡). A huge shoutout to CP-Algorithms for their incredible documentation on this topic 👇 https://lnkd.in/gpTVA_9h #DSA #CompetitiveProgramming #Java #SoftwareEngineering #ComputerScience
To view or add a comment, sign in
-
-
𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐃𝐚𝐢𝐥𝐲 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞: 1784.Check if Binary String Has At Most One Segment of Ones Today’s challenge was a short but insightful problem that demonstrates how recognizing patterns in a binary string can lead to an extremely elegant solution. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐮𝐦𝐦𝐚𝐫𝐲: We are given a binary string s consisting only of '0' and '1'. The task is to determine whether the string contains at most one continuous segment of '1'. In other words, once a '0' appears after a '1', there should not be another '1' later in the string. If there is more than one segment of '1', return false. Otherwise, return true. 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: The key observation is very simple. If a binary string has more than one segment of '1', the pattern "01" must appear somewhere in the string. Why? A valid string with only one segment of ones looks like: 0001111000 But an invalid string with multiple segments would look like: 11100111 Notice the transition "01" which indicates that ones started again after a zero. Therefore, the entire problem reduces to checking whether the substring "01" exists. If "01" is present → there are multiple segments of '1'. If "01" is absent → there is at most one segment. This allows us to solve the problem in a single line using the built-in string function. 𝐂𝐨𝐝𝐞 𝐒𝐧𝐢𝐩𝐩𝐞𝐭 (Java): class Solution { public boolean checkOnesSegment(String s) { return !s.contains("01"); } } 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 𝐀𝐧𝐚𝐥𝐲𝐬𝐢𝐬: Time Complexity: O(n) Space Complexity: O(1) We scan the string once to check if the pattern "01" exists. 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬: Sometimes the best solution is identifying a simple pattern instead of simulating the entire process. Understanding how transitions occur in binary strings can simplify many problems. Leveraging built-in string functions can make solutions both clean and efficient. A great reminder that even small problems can reinforce strong pattern-recognition skills. #LeetCode #DSA #Java #ProblemSolving #Algorithms #BinaryStrings #CodingPractice #Consistency #100DaysOfCode #LearningJourney
To view or add a comment, sign in
-
-
𝗧𝗼𝗱𝗮𝘆’𝘀 𝗶𝗻𝘁𝗲𝗿𝗲𝘀𝘁𝗶𝗻𝗴 𝗽𝗿𝗼𝗯𝗹𝗲𝗺: LeetCode 1980 – Find Unique Binary String Given n unique binary strings of length n, the task is to construct a binary string that does not exist in the list. The brute-force idea would explore up to (2^n) possibilities. But there’s a much cleaner insight: if we flip the i-th bit of the i-th string and build a new string from those flips, the result is guaranteed to differ from every string in the list. This technique comes from 𝗖𝗮𝗻𝘁𝗼𝗿’𝘀 𝗱𝗶𝗮𝗴𝗼𝗻𝗮𝗹 𝗮𝗿𝗴𝘂𝗺𝗲𝗻𝘁, a concept from mathematics that turns out to be surprisingly useful in algorithm design. Always enjoyable when a simple idea leads to an optimal 𝗢(𝗻) solution. #leetcode #algorithms #datastructures #problemSolving #softwareengineering #java
To view or add a comment, sign in
-
-
Regex is the one thing every developer pretends to understand. So I built something about it. Regex IntelliSense — a VS Code extension that explains regex on hover, in plain English. No context switching, no ChatGPT prompts. What it does: → Detects 25+ named patterns (email, URL, UUID,…) → Breaks down each component of unknown patterns → Shows example matches inline → Works across JS, TS, Python, Java, Go, Ruby + more It's free on the VS Code Marketplace. If regex has ever made you feel stupid — this one's for you. #VSCode #Regex
To view or add a comment, sign in
-
Code Review Graph – 5x Fewer Tokens with Claude Code (MCP) Claude reads your entire codebase on every code review. 200 files. 150k tokens. Every. Single. Time. There's a smarter way — and it's a knowledge graph. `code-review-graph` is an open-source tool that builds a structural graph of your codebase using Tree-sitter, then gives Claude Code only what's actually relevant: → Changed files → Files in the blast radius (dependents, callers, importers) → Nothing else The result: ✅ 5–10x fewer tokens per review ✅ Automatic impact/blast-radius analysis ✅ Incremental updates in <2s after the first build ✅ Supports 12+ languages (Python, TS, Go, Rust, Java, C# and more) ✅ Native Claude Code integration via MCP The architecture is clean: Tree-sitter parses your code → SQLite + NetworkX stores the graph → Git diff detects what changed → MCP server exposes it to Claude. You get three review workflows out of the box: /code-review-graph:build-graph /code-review-graph:review-delta /code-review-graph:review-pr This is exactly the kind of tooling that makes AI-assisted development practical at scale — not just a demo, but a real workflow improvement. Have you thought about token costs in your AI dev workflow? Drop your approach below — I'd love to compare notes. #ClaudeCode #SystemDesign #MCP
To view or add a comment, sign in
-
Explore related topics
- Approaches to Array Problem Solving for Coding Interviews
- Common Algorithms for Coding Interviews
- Java Coding Interview Best Practices
- Strategies for Solving Algorithmic Problems
- Prioritizing Problem-Solving Skills in Coding Interviews
- Key DSA Patterns for Google and Twitter Interviews
- Importance of Algorithms in Software Engineering Roles
- Pattern Matching in Large Language Model Problem Solving
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