Count of alphabets having ASCII value less than and greater than k

Given a string, the task is to count the number of alphabets having ASCII values less than and greater than or equal to a given integer k.

Examples:

Input: str = “GeeksForGeeks”, k = 90
Output:3, 10
G, F, G have ascii values less than 90.
e, e, k, s, o, r, e, e, k, s have ASCII values greater than or equal to 90

Input: str = “geeksforgeeks”, k = 90
Output: 0, 13

Approach: Start traversing the string and check if the current character has an ASCII value less than k. If yes then increment the count. So, the Remaining characters will have ASCII values greater than or equal to k. So, print len_of_String – count for characters with ASCII values greater than or equal to k.

Below is the implementation of the above approach:

C++

 `// C++ implementation of the above approach``#include ``using` `namespace` `std;` `// Function to count the number of``// characters whose ascii value is less than k``int` `CountCharacters(string str, ``int` `k)``{``    ``// Initialising the count to 0``    ``int` `cnt = 0;` `    ``int` `len = str.length();``    ``for` `(``int` `i = 0; i < len; i++) {``        ``// Incrementing the count``        ``// if the value is less``        ``if` `(str[i] < k)``            ``cnt++;``    ``}` `    ``// return the count``    ``return` `cnt;``}` `// Driver code``int` `main()``{``    ``string str = ``"GeeksForGeeks"``;``    ``int` `k = 90;` `    ``int` `count = CountCharacters(str, k);``    ``cout << ``"Characters with ASCII values"``            ``" less than K are "``         ``<< count;` `    ``cout << ``"\nCharacters with ASCII values"``            ``" greater than or equal to K are "``         ``<< str.length() - count;` `    ``return` `0;``}`

Java

 `// Java implementation of the above approach``import` `java.util.*;` `class` `GFG {``    ` `// Function to count the number of``// characters whose ascii value is less than k``static` `int` `CountCharacters(String str, ``int` `k)``{``    ``// Initialising the count to 0``    ``int` `cnt = ``0``;` `    ``int` `len = str.length();``    ``for` `(``int` `i = ``0``; i < len; i++) {``        ``// Incrementing the count``        ``// if the value is less``        ``if` `(((``int``)str.charAt(i)) < k)``            ``cnt++;``    ``}` `    ``// return the count``    ``return` `cnt;``}` `// Driver code``public` `static` `void` `main(String args[])``{``    ``String str = ``"GeeksForGeeks"``;``    ``int` `k = ``90``;` `    ``int` `count = CountCharacters(str, k);``    ``System.out.println(``"Characters with ASCII values less than K are "``+count);` `    ``System.out.println(``"Characters with ASCII values greater than or equal to K are "``+(str.length() - count));` `}``}`

Python3

 `# Python3 implementation of the``# above approach` `# Function to count the number of``# characters whose ascii value is ``# less than k``def` `CountCharacters(``str``, k):` `    ``# Initialising the count to 0``    ``cnt ``=` `0` `    ``l ``=` `len``(``str``)``    ``for` `i ``in` `range``(l):``        ` `        ``# Incrementing the count``        ``# if the value is less``        ``if` `(``ord``(``str``[i]) < k):``            ``cnt ``+``=` `1` `    ``# return the count``    ``return` `cnt` `# Driver code``if` `__name__ ``=``=` `"__main__"``:` `    ``str` `=` `"GeeksForGeeks"``    ``k ``=` `90` `    ``count ``=` `CountCharacters(``str``, k)``    ``print` `(``"Characters with ASCII values"``,``                ``"less than K are"``, count)` `    ``print` `(``"Characters with ASCII values"``,``           ``"greater than or equal to K are"``,``                           ``len``(``str``) ``-` `count)` `# This code is contributed by ita_c`

C#

 `// C# implementation of the above approach ``using` `System;``class` `GFG { ``    ` `// Function to count the number of ``// characters whose ascii value is less than k ``static` `int` `CountCharacters(String str, ``int` `k) ``{ ``    ``// Initialising the count to 0 ``    ``int` `cnt = 0; ` `    ``int` `len = str.Length; ``    ``for` `(``int` `i = 0; i < len; i++) ``    ``{ ``        ``// Incrementing the count ``        ``// if the value is less ``        ``if` `(((``int``)str[i]) < k) ``            ``cnt++; ``    ``} ` `    ``// return the count ``    ``return` `cnt; ``} ` `// Driver code ``public` `static` `void` `Main() ``{ ``    ``String str = ``"GeeksForGeeks"``; ``    ``int` `k = 90; ``    ``int` `count = CountCharacters(str, k); ``    ``Console.WriteLine(``"Characters with ASCII values"` `+``                        ``"less than K are "` `+ count); ` `    ``Console.WriteLine(``"Characters with ASCII values greater"` `+``                    ``"than or equal to K are "``+(str.Length - count)); ``} ``} ` `// This code is contributed by princiraj1992`

Javascript

 ``

PHP

 ``

Output
```Characters with ASCII values less than K are 3
Characters with ASCII values greater than or equal to K are 10
```

Complexity Analysis:

• Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time
• Auxiliary Space: O(1), as we are not using any extra space.

Approach 2: Dynamic Programming:

Here’s a step-by-step explanation of how the DP algorithm works:

• Initialization: We first initialize a 2D array dp of size len x 128 (where len is the length of the string and 128 is the number of possible ASCII values) to all zeros. We also fill in the base cases, which are the values of dp[0][j] for all j. dp[0][j] is 1 if the first character of the string has ASCII value less than or equal to j, and 0 otherwise.
• Computing the DP table: We iterate through the string str from left to right. For each character str[i] and each possible ASCII value j, we compute dp[i][j] using the recurrence relation:
• dp[i][j] = dp[i-1][j] + (str[i] <= j)
• The first term on the right-hand side represents the number of characters in str[0:i-1] whose ASCII value is less than or equal to j. The second term is 1 if str[i] has ASCII value less than or equal to j, and 0 otherwise. By adding these two terms, we get the number of characters in str[0:i] whose ASCII value is less than or equal to j.
• Final answer: The final answer is given by dp[len-1][k-1], which represents the number of characters in the entire string str whose ASCII value is less than or equal to k-1.
• Output: We output the count of characters whose ASCII value is less than k, which is dp[len-1][k-1]. We also output the count of characters whose ASCII value is greater than or equal to k, which is str.length() – dp[len-1][k-1].

Here is the code of the above DP approach:

C++

 `#include ``using` `namespace` `std;` `// Function to count the number of``// characters whose ascii value is less than k``int` `CountCharacters(string str, ``int` `k)``{``// Initialising the 2D array to 0``int` `len = str.length();``int` `dp[len][128] = {0};``  ``// Filling in the base cases``for` `(``int` `j = 0; j < 128; j++) {``    ``dp[0][j] = (str[0] <= j);``}` `// Computing the DP table``for` `(``int` `i = 1; i < len; i++) {``    ``for` `(``int` `j = 0; j < 128; j++) {``        ``dp[i][j] = dp[i-1][j] + (str[i] <= j);``    ``}``}` `// return the count``return` `dp[len-1][k-1];``}` `// Driver code``int` `main()``{``string str = ``"GeeksForGeeks"``;``int` `k = 90;``  ``int` `count = CountCharacters(str, k);``cout << ``"Characters with ASCII values"``        ``" less than K are "``     ``<< count;` `cout << ``"\nCharacters with ASCII values"``        ``" greater than or equal to K are "``     ``<< str.length() - count;` `return` `0;``}`

Java

 `import` `java.util.Arrays;` `public` `class` `CharacterCount {` `    ``// Function to count the number of characters``    ``// whose ASCII value is less than k``    ``static` `int` `countCharacters(String str, ``int` `k)``    ``{``        ``int` `len = str.length();``        ``int``[][] dp``            ``= ``new` `int``[len]``                     ``[``128``]; ``// Initialize a 2D array for DP` `        ``// Filling in the base cases``        ``for` `(``int` `j = ``0``; j < ``128``; j++) {``            ``dp[``0``][j] = (str.charAt(``0``) <= j) ? ``1` `: ``0``;``        ``}` `        ``// Computing the DP table``        ``for` `(``int` `i = ``1``; i < len; i++) {``            ``for` `(``int` `j = ``0``; j < ``128``; j++) {``                ``dp[i][j] = dp[i - ``1``][j]``                           ``+ ((str.charAt(i) <= j) ? ``1` `: ``0``);``            ``}``        ``}` `        ``// Return the count``        ``return` `dp[len - ``1``][k - ``1``];``    ``}` `    ``public` `static` `void` `main(String[] args)``    ``{``        ``String str = ``"GeeksForGeeks"``;``        ``int` `k = ``90``;``        ``int` `count = countCharacters(str, k);``        ``System.out.println(``            ``"Characters with ASCII values less than K are "``            ``+ count);``        ``System.out.println(``            ``"Characters with ASCII values greater than or equal to K are "``            ``+ (str.length() - count));``    ``}``}`

Python

 `# Function to count the number of characters``# whose ASCII value is less than k`  `def` `count_characters(s, k):``    ``# Get the length of the string``    ``n ``=` `len``(s)` `    ``# Initialize a 2D array to store counts``    ``dp ``=` `[[``0``] ``*` `128` `for` `_ ``in` `range``(n)]` `    ``# Filling in the base cases``    ``for` `j ``in` `range``(``128``):``        ``dp[``0``][j] ``=` `int``(``ord``(s[``0``]) <``=` `j)` `    ``# Computing the DP table``    ``for` `i ``in` `range``(``1``, n):``        ``for` `j ``in` `range``(``128``):``            ``dp[i][j] ``=` `dp[i ``-` `1``][j] ``+` `int``(``ord``(s[i]) <``=` `j)` `    ``# Return the count``    ``return` `dp[n ``-` `1``][k ``-` `1``]`  `# Driver code``if` `__name__ ``=``=` `"__main__"``:``    ``s ``=` `"GeeksForGeeks"``    ``k ``=` `90``    ``count ``=` `count_characters(s, k)``    ``print``(``"Characters with ASCII values less than K are"``, count)``    ``print``(``"Characters with ASCII values greater than or equal to K are"``, ``len``(s) ``-` `count)`

C#

 `using` `System;` `namespace` `CharacterCount {``class` `Program {``    ``// Function to count the number of``    ``// characters whose ASCII value is less than k``    ``static` `int` `CountCharacters(``string` `str, ``int` `k)``    ``{``        ``// Initialising the 2D array to 0``        ``int` `len = str.Length;``        ``int``[][] dp = ``new` `int``[len][];` `        ``for` `(``int` `i = 0; i < len; i++) {``            ``dp[i] = ``new` `int``[128];``        ``}` `        ``// Filling in the base cases``        ``for` `(``int` `j = 0; j < 128; j++) {``            ``dp[0][j] = (str[0] <= j) ? 1 : 0;``        ``}` `        ``// Computing the DP table``        ``for` `(``int` `i = 1; i < len; i++) {``            ``for` `(``int` `j = 0; j < 128; j++) {``                ``dp[i][j] = dp[i - 1][j]``                           ``+ ((str[i] <= j) ? 1 : 0);``            ``}``        ``}` `        ``// return the count``        ``return` `dp[len - 1][k - 1];``    ``}` `    ``// Driver code``    ``static` `void` `Main(``string``[] args)``    ``{``        ``string` `str = ``"GeeksForGeeks"``;``        ``int` `k = 90;``        ``int` `count = CountCharacters(str, k);``        ``Console.WriteLine(``            ``"Characters with ASCII values less than K are "``            ``+ count);``        ``Console.WriteLine(``            ``"Characters with ASCII values greater than or equal to K are "``            ``+ (str.Length - count));``    ``}``}``}`

Javascript

 `// JavaScript code for the above approach``function` `countCharacters(str, k) {``    ``const len = str.length;``    ``const dp = ``new` `Array(len).fill(0).map(() => ``new` `Array(128).fill(0));` `    ``// Filling in the base cases``    ``for` `(let j = 0; j < 128; j++) {``        ``dp[0][j] = str.charCodeAt(0) <= j ? 1 : 0;``    ``}` `    ``// Computing the DP table``    ``for` `(let i = 1; i < len; i++) {``        ``for` `(let j = 0; j < 128; j++) {``            ``dp[i][j] = dp[i - 1][j] + (str.charCodeAt(i) <= j ? 1 : 0);``        ``}``    ``}` `    ``// Return the count``    ``return` `dp[len - 1][k - 1];``}` `// Driver code to test above function``const str = ``"GeeksForGeeks"``;``const k = 90;``const count = countCharacters(str, k);` `console.log(``"Characters with ASCII values less than K are "` `+ count);``console.log(``"Characters with ASCII values greater than or equal to K are "` `+ (str.length - count));``// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL`

Output
```Characters with ASCII values less than K are 3
Characters with ASCII values greater than or equal to K are 10
```

Time complexity:  O(len * 128) because we iterate through the string str once and compute dp[i][j] for all i and j.
Space complexity: is O(len * 128) because we use a 2D array of size len x 128 to store the DP table.

Previous
Next