🧠 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
Count Special Characters in a String
More Relevant Posts
-
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
-
-
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
-
-
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 I tackled the Sequence Equation problem, which involves working with permutations and index mapping. 🔍 Problem Insight: Given a permutation p, find values of y such that: 👉 p[p[y]] = x for all x from 1 to n 💡 Key Idea: Instead of brute force, I used: Position mapping for fast lookup Double indexing trick (pos[pos[x]]) 🚀 Why this works: It reduces complexity from O(n²) to O(n), making it highly efficient. 🧠 What I learned: Importance of inverse mapping Optimizing lookup operations Writing clean and efficient Java code 📌 Example: Input: [5, 2, 1, 3, 4] Output: [4, 2, 5, 1, 3] 🔖 Tags #Java #DataStructures #Algorithms #CodingChallenge #ProblemSolving #100DaysOfCode #DeveloperJourney #SoftwareDeveloper #Hackerrank #CodingPractice #TechLearning
To view or add a comment, sign in
-
-
💡 Day 44 – Solved Problem #208: "Implement Trie (Prefix Tree)" using Java! Today I explored an important data structure used in real-world applications like autocomplete and search systems 🌳 🔍 Problem: Design a Trie (Prefix Tree) with insert, search, and prefix search operations. 🧠 Key Insight: A Trie stores words character by character, allowing efficient prefix-based operations. 🚀 Approach: Used an array of size 26 at each node to represent lowercase English letters and a boolean flag to mark complete words. ⏱ Time Complexity: O(m) per operation 📦 Space Complexity: O(26 × m) This problem helped me understand how powerful tree-based structures can optimize string operations! #Day50 #LeetCode #Problem208 #Java #Trie #DataStructures #CodingJourney
To view or add a comment, sign in
-
-
⚡ How to Handle Race Conditions in Python (Backend Systems) Race conditions happen when multiple threads/processes access and modify shared data at the same time, leading to inconsistent results. 👉 In simple terms: the final output depends on “who executes first”. This is a serious issue in backend systems like payments, bookings, and inventory management. 🛠️ How I handle Race Conditions: ✔️ Use Locks (Mutex) Ensure only one thread can access critical code at a time. ✔️ Use Atomic Operations Perform updates in a single, indivisible step. ✔️ Thread Synchronization Control execution flow using semaphores, events, etc. ✔️ Database Transactions Use proper isolation levels and row-level locking. ✔️ Better Design Reduce shared state by using queues and stateless services. 💡 Key takeaway: Concurrency is powerful, but without control, it breaks data integrity. Always protect shared resources or eliminate them where possible. #Python #BackendDevelopment #SystemDesign #Concurrency #SoftwareEngineering #Performance
To view or add a comment, sign in
-
Solved a pretty interesting Trie-based string problem today. https://lnkd.in/gYNF8uda The problem sounded simple at first: Find the word with the longest matching suffix. If multiple words match, choose the shortest one. If there’s still a tie, return the smaller index. The interesting part was realizing that suffix matching becomes much easier if you just reverse every string. running → gninnur king → gnik ing → gni After reversing: suffix matching → prefix matching And since Tries are naturally good at prefix matching, the whole problem becomes much cleaner. My approach was: Reverse all container words Insert them into a Trie At every Trie node, store: the minimum word length the corresponding index Reverse query strings and traverse normally What I liked about this problem was that the optimization didn’t come from adding more complexity. It came from changing the perspective of the problem itself. Complexities were pretty efficient too: Insertion: O(total characters) Query: O(total query characters) Concepts involved: Trie Data Structure Prefix Matching String Manipulation Greedy Optimization Problems like these are a good reminder that sometimes one small observation can simplify the entire solution. #Trie #DSA #Algorithms #Java #Programming
To view or add a comment, sign in
-
-
𝗧𝗵𝗶𝘀 𝗔𝗿𝗿𝗮𝘆 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗟𝗼𝗼𝗸𝗲𝗱 𝗟𝗶𝗸𝗲 𝗚𝗿𝗲𝗲𝗱𝘆 𝗗𝗲𝗹𝗲𝘁𝗶𝗼𝗻𝘀 — 𝗜𝘁 𝗪𝗮𝘀 𝗔𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗮 𝗗𝗣 𝗜𝗻𝗲𝗾𝘂𝗮𝗹𝗶𝘁𝘆 🔥 A position i is fixed if nums[i] == i. You may delete elements; the rest shift left. 𝗚𝗼𝗮𝗹 -> 𝗺𝗮𝘅𝗶𝗺𝗶𝘇𝗲 𝗳𝗶𝘅𝗲𝗱 𝗽𝗼𝗶𝗻𝘁𝘀. The unlock was to stop simulating deletions and focus on the condition that must hold. 🧩 𝗞𝗲𝘆 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 If index i becomes fixed: i−deletions = nums[i] => target = i−nums[i] For two indices j -> i to both work: i−j ≥ a[i]−a[j] => i−a[i] ≥ j−a[j] So transitions depend only on non-decreasing target values. This turns the problem into DP on target. ⚠️ 𝗢𝗻𝗲 𝗠𝗼𝗿𝗲 𝗖𝗼𝗻𝘀𝘁𝗿𝗮𝗶𝗻𝘁 We must also ensure nums[j] < nums[i]. To guarantee this, sort pairs (nums[i], i) and process in increasing value order. ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 1. Ignore indices where i < nums[i] (impossible to fix) 2. Compute target = i - nums[i] 3. Sort pairs (nums[i], i) 4. Build DP: dp[target]=1+max(dp[0…target]) 5. Use a Segment Tree to get fast range maximum 6. The maximum DP value is the answer 🔑 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴𝘀 1. Don’t simulate deletions — translate them into constraints 2. Many array problems reduce to DP on derived values 3. When DP needs fast prefix maximum → Segment Tree 4. Sorting can enforce hidden transition rules cleanly #DSA #Algorithms #DynamicProgramming #SegmentTree #ProblemSolving #CodingInterview #Java #DataStructures #CompetitiveProgramming #InterviewPrep #TechLearning #ArrayProblems #Optimization #CodingJourney
To view or add a comment, sign in
-
-
Day 67 #SDE tree views and tree serialization patterns. Solved: • Bottom View of Binary Tree • Find Duplicate Subtrees Key Learning: • “Bottom View of Binary Tree” uses level order traversal (BFS) with horizontal distance mapping to capture the last visible node at each level. • “Find Duplicate Subtrees” involves tree serialization + hashing, where identical subtree structures are detected using string representation or maps. #LeetCode #DSA #BinaryTree #Trees #Algorithms #Java #SoftwareEngineering
To view or add a comment, sign in
-
#DSAChallengeDay53 Today’s challenge was a neat exercise in bit manipulation + set intersection logic 🔠⚡ 📌 Problem Solved Today (LeetCode - 3120): Count the Number of Special Characters I ✅ Logic: The task is to count characters that appear in both lowercase and uppercase in the string. I solved this using bit manipulation for efficient tracking: ✅ Traversed the string and tracked lowercase characters using a bitmask ✅ Tracked uppercase characters using a separate bitmask ✅ Used bitwise AND (lower & upper) to find common characters ✅ Counted set bits using Integer.bitCount() to get the final answer 💡 Learnings: 🔹 Bit manipulation is a powerful way to optimize space and speed for character tracking 🔹 Using bitmasks avoids extra data structures like sets/maps 🔹 The intersection of two bitmasks directly gives the required result 🔹 Efficient solution with O(n) time and O(1) space 🚀 This problem reinforced how low-level techniques like bit operations can simplify seemingly straightforward problems and make solutions more elegant. #DSAChallengeDay53 #100DaysOfDSA #LeetCode #LeetCodeDailyChallenge #BitManipulation #Java #DSA #CodingJourney #KeepCoding #OptimizationTricks #geekstreak2025 #personalguidanceprogram #pgpbyanchal
To view or add a comment, sign in
-