Bigger Is Greater Hackerrank Solution C -
Given a word (string of lowercase English letters), find the of its characters. If no such permutation exists (i.e., the string is already the largest possible), return "no answer" .
while (t--) char word[101]; // Assuming max length 100, +1 for null terminator scanf("%s", word);
char* biggerIsGreater(char* str) int n = strlen(str); int i, j;
void reverse(char *str, int start, int end) while (start < end) swap(&str[start], &str[end]); start++; end--; bigger is greater hackerrank solution c
// Swap str[i] and str[min_idx] char temp = str[i]; str[i] = str[min_idx]; str[min_idx] = temp;
while (t--) char str[101]; scanf("%s", str); biggerIsGreater(str);
The approach to solving this problem is to find the first pair of digits from the right that are in increasing order, and then swap the first digit with the smallest digit on its right that is greater than it. Finally, we sort the digits on the right of the swapped pair in ascending order. Given a word (string of lowercase English letters),
#include #include #include void swap(char *a, char *b) char temp = *a; *a = *b; *b = temp; void reverse(char *str, int start, int end) while (start < end) swap(&str[start], &str[end]); start++; end--; char* biggerIsGreater(char* s) int n = strlen(s); int i = n - 2; // Step 1: Find the rightmost character smaller than its neighbor while (i >= 0 && s[i] >= s[i + 1]) i--; // If no pivot is found, the string is the largest possible if (i < 0) return "no answer"; // Step 2: Find the rightmost character larger than the pivot int j = n - 1; while (s[j] <= s[i]) j--; // Step 3: Swap pivot and successor swap(&s[i], &s[j]); // Step 4: Reverse the suffix to get the smallest possible increase reverse(s, i + 1, n - 1); return s; int main() int T; scanf("%d", &T); while (T--) char s[101]; scanf("%s", s); char* result = biggerIsGreater(s); printf("%s\n", result); return 0; Use code with caution. Key Takeaways for Optimization
Input: A string of digits. Output: The largest possible number that can be formed by rearranging the digits, or "no" if no larger number can be formed.
Reverse suffix after index 0: Reverse "hcd" → "dch" . Result: "kdch" . Finally, we sort the digits on the right
// Step 4: Reverse the suffix after pivot reverse(str, i + 1, n - 1);
Here is a comprehensive guide and a high-performance C solution for this challenge. Understanding the Logic
Here’s a clean, efficient C implementation: