Counting 'A' before 'G' in a String

👉 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

To view or add a comment, sign in

Explore content categories