🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/dGC2Q2G4 This solution counts "special" characters in a string. A character is special if it appears in both lowercase and uppercase forms within the word. A vector of 26 pairs is set up, one for each letter of the alphabet. Each pair contains two booleans. The first boolean tracks if the lowercase version of the letter has been seen, and the second tracks if the uppercase version has been seen. Both start as false. The loop goes through each character in the input string. If the character is lowercase (ASCII value >= 'a'), it calculates the alphabet index using ch - 'a' and sets the first boolean in that slot to true. If the character is uppercase, it calculates the index using ch - 'A' and sets the second boolean to true. Both 'a' and 'A' map to index 0, 'b' and 'B' to index 1, and so on. This connects the tracking of lowercase and uppercase letters under the same slot. After finishing the first loop, a second loop checks all 26 slots. If both booleans in a slot are true, it indicates that the letter appeared as both lowercase and uppercase at least once, making it special. The counter is then increased. The function returns the final count of special characters. 👉 My Solution: https://lnkd.in/dEY5RndW If you found this helpful, feel free to ⭐ the repo or connect! 🙂 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering
Counting Special Characters in a String - LeetCode Challenge
More Relevant Posts
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/dQ2wXa68 The solution tracks the positions of both lowercase and uppercase letters for each character in the alphabet. It uses a vector of 26 pairs. The `first` element stores the last occurrence index of the lowercase letter, and the `second` element holds the first occurrence index of the uppercase letter. As we go through the string, whenever a lowercase letter is found, its index updates in `first`, making sure the last lowercase position is recorded. For an uppercase letter, `second` gets assigned only once, so it keeps the first uppercase occurrence. After going through the whole string, we check each character from 'a' to 'z'. A character is considered special if it appears in both lowercase and uppercase forms, and all lowercase occurrences appear before all uppercase occurrences. This condition is met when the last lowercase index is less than or equal to the first uppercase index (`first <= second`). The total count of such characters is then returned as the final answer. The time complexity is O(n + 26), which simplifies to O(n). The space complexity is O(26), or O(1). 👉 My Solution: https://lnkd.in/dc76SN3Z If you found this helpful, feel free to ⭐ the repo or connect! 🙂 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering
To view or add a comment, sign in
-
-
I ran into a subtle bug today while solving a string problem on LeetCode, and it’s a good reminder that “almost correct” logic can still fail in edge cases. The task looked straightforward: replace every '?' in a string with lowercase letters to make the final result lexicographically smallest. My approach? Track character usage and always pick the smallest available letter. It worked… until it didn’t. One test case broke everything: "abcdefghijklmnopqrstuvwxy??" My output: "abcdefghijklmnopqrstuvwxyz a" Expected: "abcdefghijklmnopqrstuvwxyz z" At first glance, both seem valid. But the issue wasn’t about minimizing globally—it was about respecting local constraints. I had ignored a critical rule: Adjacent characters must not be equal. So while I was optimizing for frequency and lexicographic order, I completely missed the importance of neighbor awareness. The fix was simple in hindsight: For each '?', choose the smallest character that: - is not equal to the previous character - is not equal to the next character (if already fixed) That tiny constraint changed the entire behavior of the solution. Key takeaway: In algorithmic problems, especially greedy ones, local constraints often override global heuristics. If your solution feels “almost right,” test it against edge cases where assumptions break. This was a small bug—but a great lesson in thinking beyond the obvious optimization. #DataStructures #Algorithms #ProblemSolving #LeetCode #Programming #CPlusPlus
To view or add a comment, sign in
-
Daily LeetCode done ✅ Today’s question: Number of Special Characters 🚀 At first glance, the problem looks very straightforward… but the interesting part was handling the order condition carefully. 💡 Idea behind my approach: We need to count characters where: ✅ lowercase appears first ✅ uppercase appears later So instead of storing frequencies, I tracked INDEX POSITIONS. 🔹 For lowercase letters: → store the latest occurrence index 🔹 For uppercase letters: → store only the first occurrence index using putIfAbsent() Then for every lowercase character: if lastIndex(lowercase) < firstIndex(UPPERCASE) ➡️ it becomes a valid “special character”. Example: aAbBc ✔️ ‘a’ appears before ‘A’ ✔️ ‘b’ appears before ‘B’ Answer = 2 One thing I’m enjoying lately: trying to make solutions cleaner every time I revisit patterns. 🚀 Even simple problems improve: ⚡ map usage ⚡ edge case thinking ⚡ observation skills ⚡ implementation clarity That consistency matters more than difficulty tags. 💯 #LeetCode #Java #DSA #ProblemSolving #CodingJourney #CompetitiveProgramming #Algorithms #SoftwareEngineering #DailyCoding LinkedIn: @rajgupta40
To view or add a comment, sign in
-
-
🧠 Day 245 — Password Strength 🔐📚 Today solved a Hashing + Character Classification problem: calculating password strength using distinct character categories. 📌 Problem Goal Given a password string, calculate its total strength based on: ✔️ Distinct lowercase letters → +1 ✔️ Distinct uppercase letters → +2 ✔️ Distinct digits → +3 ✔️ Distinct special chars (! @ # $) → +5 Each character contributes only once. 🔹 Core Idea The key observation: duplicates should not contribute multiple times. So: ✔️ Track already processed characters using a HashSet ✔️ Only score unseen characters 🔹 Approach Thinking 1️⃣ Traverse Password Check every character one by one. 2️⃣ Avoid Duplicate Contribution If character already exists in set: → Skip it Otherwise: → Calculate points → Add to HashSet 3️⃣ Character Classification Determine category using ranges: → 'a' to 'z' → lowercase → 'A' to 'Z' → uppercase → '0' to '9' → digit → ! @ # $ → special 4️⃣ Add Weighted Points Each category has different contribution values. 🧠 Key Learning ✔️ HashSet is extremely useful for uniqueness problems ✔️ Character classification is a common string-processing pattern ✔️ Sometimes problems are more about careful implementation than complex algorithms 💡 Today’s Realization This problem connects with: Hashing String traversal Character processing Frequency/uniqueness tracking The hidden skill: breaking input into meaningful categories efficiently. 🚀 Momentum Status: becoming faster at spotting clean implementation patterns. On to Day 246. #DSA #Hashing #Strings #Java #LeetCode #ProblemSolving #CodingJourney #ConsistencyWins
To view or add a comment, sign in
-
-
🧠 Day 248— Count Special Characters II 🔤📚 Today solved a string processing problem using: character tracking + indexing logic. 📌 Problem Goal Given a string, count characters where: ✔️ lowercase letter appears first ✔️ uppercase version appears later Example: → 'a' before 'A' → valid special character 🔹 Core Idea Track the latest position of lowercase characters first. Then while traversing: → if uppercase character appears AFTER its lowercase → count it as special 🔹 Approach Thinking 1️⃣ Store Lowercase Positions Create an array for: → latest occurrence of each lowercase letter This helps quickly check: “Did lowercase appear before uppercase?” 2️⃣ Traverse Again For every uppercase character: → convert to lowercase index → check stored lowercase position If: ✔️ lowercase exists ✔️ uppercase comes later → increment answer 3️⃣ Prevent Double Counting After counting a character once: → mark it invalid/reset So duplicate uppercase letters don’t increase answer again. 🧠 Key Learning ✔️ Character indexing makes string problems efficient ✔️ ASCII transformations are very powerful: → toLowerCase() → toUpperCase() ✔️ Arrays are often faster than HashMaps for fixed alphabets. 💡 Today’s Realization This problem connects with: Character frequency problems String hashing concepts Case conversion logic Index tracking patterns Main idea: → preprocess information first, → then validate conditions efficiently. 🚀 Momentum Status: String problem-solving becoming faster and cleaner. On to Day 249. #DSA #Strings #Arrays #LeetCode #Java #ProblemSolving #CodingJourney #ConsistencyWins
To view or add a comment, sign in
-
-
A small constraint can completely change how you approach a problem — I saw this clearly while practicing arrays and strings last week. I kept running into problems where the input had some hidden structure: • Array elements limited to a specific range (like 1 to n) • Strings restricted to lowercase English letters Earlier, my instinct was to use extra space — hash maps, sets, frequency arrays. But then I started asking: Do I really need extra space here? For arrays: If elements are in the range 1 to n, the array itself can act like a hash map. Using indices to mark presence or track duplicates removes the need for extra memory. For strings: When characters are limited (like a–z), we can replace hash maps with fixed-size arrays (size 26). Same idea — but more space-efficient and often faster. Problems where this showed up: • Finding duplicates / missing numbers (arrays) • Anagrams / character frequency (strings) • First missing positive What changed for me wasn’t just optimization — it was thinking in terms of constraints first. Now, before coding, I try to pause and ask: What is the input range telling me? Takeaway: Constraints aren’t just limits — they quietly guide you toward better solutions. #DSA #Algorithms #ProblemSolving #Coding
To view or add a comment, sign in
-
-
Has anyone else come across these AI screening tests for developer jobs, where you have to do some LeetCode type programming problem without the benefit of the Internet, with a web cam on you at all times, and you can't tab out of the page, and of course the whole thing is timed? My son's had to do a few of these already & I'm wondering, who the hell put these together? They don't simulate anything you'd have to do on the job. Unless you're anticipating having to hand code Dijkstra's algorithm on a crowded bus in rush hour in Notepad under threat that a terrorist will blow up the bus if you don't. WTAF, folks?
To view or add a comment, sign in
-
LeetCode POTD | Day 59 3121. Count the Number of Special Characters II Today’s problem was another character tracking problem, but this time with stricter position conditions between lowercase and uppercase letters. We had to count characters where all lowercase occurrences appeared before the uppercase occurrence. My approach: • Used a HashMap<Character, Integer> to store character positions • Traversed the string from right to left • Stored uppercase character indices directly • For lowercase characters, stored the maximum index using Math.max() • Iterated through all 26 characters and compared lowercase and uppercase positions • Increased the count only when the lowercase position appeared before the uppercase position Using reverse traversal simplified the index handling logic and made the comparisons much cleaner. What I learned today: • Traversal direction can completely simplify a problem • HashMaps are very useful for index-based character tracking • Position-based string problems require careful condition checking • Small optimizations in logic can make implementations cleaner • Character problems become easier once patterns are identified #LeetCode #DSA #Strings #HashMap #Java #ProblemSolving #CodingJourney #Algorithms #LeetCodeDailyChallenge
To view or add a comment, sign in
-
-
Today’s LeetCode Daily Problem 💻 LeetCode 3121. Count the Number of Special Characters II => Problem Task: Count Special Characters. For a character to be special, two conditions must be satisfied: • It must appear in both lowercase and uppercase. • All lowercase occurrences must come before the first uppercase occurrence. => Constraints: 1 <= word.length <= 2 * 10^5 Checking all lowercase-uppercase pairs manually would lead to an O(n^2) approach: (2 * 10^5)^2 > 10^8, which is far beyond acceptable limits. => Core Intuition: Instead of checking every pair manually, we only need: • the last occurrence of each lowercase character • the first occurrence of each uppercase character If last lowercase index < first uppercase index, then every lowercase occurrence naturally appears before every uppercase occurrence, making that character special. => One small optimization I used: Instead of initializing arrays with -1, I kept the default 0 initialization and stored indices as i+1. This avoids extra initialization work while also helping differentiate between: • 0 -> character not present • >0 -> valid stored index => Complexity • Time Complexity: O(N) • Space Complexity: O(1) => My Step-by-Step Detailed Solution with Dry Run: https://lnkd.in/eFX7iu6e Feel free to share your approach in the comments. #leetcode #leetcodedailycodingchallenge #java #dsa #programming #coding #softwareengineering #competitiveprogramming #algorithms #computerscience
To view or add a comment, sign in
-
-
Day 38 of DSA Journey 🚀 Today I solved another interesting String problem on LeetCode: 🔤 Count the Number of Special Characters I At first, the problem looked very simple: “Count characters that appear in both lowercase and uppercase.” But while solving it, I realized this problem is actually about: 👉 efficient character tracking 👉 ASCII-based indexing 👉 and optimizing lookup operations using arrays. The key insight: Instead of repeatedly searching the string, I can directly map characters using fixed-size arrays. My approach became: Create one array for lowercase letters Create another array for uppercase letters Traverse the string once Mark which characters exist Compare both arrays to count special characters The biggest realization today: Using arrays as frequency maps can drastically simplify string problems. What I learned today: 🔹 Character indexing using ASCII values 🔹 Boolean array optimization 🔹 Constant-time lookup logic 🔹 Space-time tradeoffs in strings 🔹 Clean traversal patterns One thing I’m noticing during this DSA journey: Easy problems are often testing implementation clarity, not algorithm difficulty. Because if your fundamentals are weak: indexing breaks character mapping fails edge cases get ignored conditions become messy very quickly This problem also reinforced something important: Sometimes the best solution is not complicated. It’s just organized thinking with the right data structure. What this problem actually taught me: 🔹 String Processing 🔹 Character Mapping 🔹 Array-Based Hashing 🔹 Efficient Traversal 🔹 Clean Conditional Logic Still learning. Still debugging. Still improving step by step 💪 #DSA #Java #LeetCode #Strings #Algorithms #CodingJourney #ProblemSolving #Programming #SoftwareEngineering #ComputerScience
To view or add a comment, sign in
-