Count of alphabets having ASCII value less than and greater than k
Last Updated :
11 Jul, 2025
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 <bits/stdc++.h>
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
<script>
// Javascript implementation of the above approach
// Function to count the number of
// characters whose ascii value is less than k
function CountCharacters(str,k)
{
// Initialising the count to 0
let cnt = 0;
let len = str.length;
for (let i = 0; i < len; i++) {
// Incrementing the count
// if the value is less
if (str[i].charCodeAt(0) < k)
cnt++;
}
// return the count
return cnt;
}
// Driver code
let str = "GeeksForGeeks";
let k = 90;
let count = CountCharacters(str, k);
document.write("Characters with ASCII values less than K are "+count+"<br>");
document.write("Characters with ASCII values greater than or equal to K are "+(str.length - count));
// This code is contributed by avanitrachhadiya2155
</script>
PHP
<?php
// PHP implementation of the above approach
// Function to count the number of
// characters whose ascii value is less than k
function CountCharacters($str, $k)
{
// Initialising the count to 0
$cnt = 0;
$len = strlen($str);
for ($i = 0; $i < $len; $i++)
{
// Incrementing the count
// if the value is less
if ($str[$i] < chr($k))
$cnt += 1;
}
// return the count
return $cnt;
}
// Driver code
$str = "GeeksForGeeks";
$k = 90;
$count = CountCharacters($str, $k);
echo("Characters with ASCII values" .
" less than K are " . $count);
echo("\nCharacters with ASCII values" .
" greater than or equal to K are " .
(strlen($str) - $count));
// This code contributed by Rajput-Ji
?>
OutputCharacters 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 <bits/stdc++.h>
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
OutputCharacters 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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem