Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Reduce string by performing repeated digit sum in group of K
Next article icon

Perform range sum queries on string as per given condition

Last Updated : 30 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S with lowercase alphabets only and Q queries where each query contains a pair {L, R}. For each query {L, R}, there exists a substring S[L, R], the task is to find the value of the product of the frequency of each character in substring with their position in alphabetical order. 
Note: Consider 1-based indexing.
Examples: 

Input: S = "abcd", Q = { {2, 4}, {1, 3} } 
Output: 9 6 
Explanation: 
For 1st query, 
substring is S[2, 4] = "bcd". Therefore the frequency of b, c, d are 1, 1, 1 in range 2 to 4. 
value = 2*(1) + 3*(1) + 4*(1) = 9.
For 2nd query, 
substring is S[1, 3] = "abc". Therefore the frequency of a, b, c are 1, 1, 1 in range 1 to 3. 
value = 1*(1) + 2*(1) + 3*(1) = 6.
Input: S = "geeksforgeeks", Q = { {3, 3}, {2, 6}, {1, 13} } 
Output: 5 46 133 

Naive Approach: The naive idea is to traverse for each ranges [L, R] in the query and keep the count of each character in an array. After traversing the range find the value of the expression 1*(occurrences of 'a') + 2*(occurrences of 'b') + 3*(occurrences of 'c') + ..+ 26*(occurrences of 'z'). 
Time Complexity: O(N*Q), where N is the length of the given string. 
Auxiliary Space: O(1)
Efficient Approach: The idea is to use the Prefix Sum of the whole string by which we can perform each query in constant time. Below are the steps: 

  1. Create an array arr[] of length equals to the length of the string.
  2. Traverse the given string and for each corresponding index i in the string, assign arr[i] the value of current character - 'a'.
  3. Find the prefix sum of the array arr[]. This prefix sum array will given sum of occurrence of all characters till each index i.
  4. Now for each query(say {L, R}) the value of arr[R - 1] - arr[L - 2] will give the value of the given expression.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to perform range sum queries // on string as per the given condition void Range_sum_query(string S,                      vector<pair<int, int> > Query) {     // Initialize N by string size     int N = S.length();      // Create array A[] for prefix sum     int A[N];      A[0] = S[0] - 'a' + 1;      // Iterate till N     for (int i = 1; i < N; i++) {         A[i] = S[i] - 'a' + 1;         A[i] = A[i] + A[i - 1];     }      // Traverse the queries     for (int i = 0; i < Query.size(); i++) {          if (Query[i].first == 1) {              // Check if L == 1 range             // sum will be A[R-1]             cout << A[(Query[i].second) - 1]                  << endl;         }          else {              // Condition if L > 1 range sum             // will be A[R-1] - A[L-2]             cout << A[(Query[i].second) - 1]                         - A[(Query[i].first) - 2]                  << endl;         }     } }  // Driver Code int main() {     // Given string     string S = "abcd";      vector<pair<int, int> > Query;      // Given Queries     Query.push_back(make_pair(2, 4));     Query.push_back(make_pair(1, 3));      // Function call     Range_sum_query(S, Query);     return 0; } 
Java
// Java program for the above approach import java.util.*;  class GFG{      static class pair {      int first, second;      public pair(int first, int second)      {          this.first = first;          this.second = second;      }  }   // Function to perform range sum queries // on String as per the given condition static void Range_sum_query(String S,                             Vector<pair> Query) {          // Initialize N by String size     int N = S.length();      // Create array A[] for prefix sum     int []A = new int[N];      A[0] = S.charAt(0) - 'a' + 1;      // Iterate till N     for(int i = 1; i < N; i++)     {         A[i] = S.charAt(i) - 'a' + 1;         A[i] = A[i] + A[i - 1];     }      // Traverse the queries     for(int i = 0; i < Query.size(); i++)     {         if (Query.get(i).first == 1)         {                          // Check if L == 1 range             // sum will be A[R-1]             System.out.print(                 A[(Query.get(i).second) - 1] + "\n");         }          else          {                          // Condition if L > 1 range sum             // will be A[R-1] - A[L-2]             System.out.print(                 A[(Query.get(i).second) - 1] -                 A[(Query.get(i).first) - 2] + "\n");         }     } }  // Driver Code public static void main(String[] args) {          // Given String     String S = "abcd";      Vector<pair> Query = new Vector<pair>();      // Given Queries     Query.add(new pair(2, 4));     Query.add(new pair(1, 3));      // Function call     Range_sum_query(S, Query); } }  // This code is contributed by Rajput-Ji  
Python3
# Python3 program for the above approach   # Function to perform range sum queries # on string as per the given condition def Range_sum_query(S, Query):      # Initialize N by string size     N = len(S)      # Create array A[] for prefix sum     A = [0] * N      A[0] = ord(S[0]) - ord('a') + 1      # Iterate till N     for i in range(1, N):         A[i] = ord(S[i]) - ord('a') + 1         A[i] = A[i] + A[i - 1]      # Traverse the queries     for i in range(len(Query)):         if(Query[i][0] == 1):              # Check if L == 1 range             # sum will be A[R-1]             print(A[Query[i][1] - 1])          else:              # Condition if L > 1 range sum             # will be A[R-1] - A[L-2]             print(A[Query[i][1] - 1] -                   A[Query[i][0] - 2])  # Driver Code  # Given string S = "abcd"  Query = []  # Given Queries Query.append([2, 4]) Query.append([1, 3])  # Function call  Range_sum_query(S, Query)  # This code is contributed by Shivam Singh 
C#
// C# program for the above approach using System; using System.Collections.Generic;   class GFG{    class pair   {     public int first, second;     public pair(int first, int second)     {       this.first = first;       this.second = second;     }   }    // Function to perform range sum queries   // on String as per the given condition   static void Range_sum_query(String S, List<pair> Query)   {      // Initialize N by String size     int N = S.Length;      // Create array []A for prefix sum     int[] A = new int[N];      A[0] = S[0] - 'a' + 1;      // Iterate till N     for (int i = 1; i < N; i++)     {       A[i] = S[i] - 'a' + 1;       A[i] = A[i] + A[i - 1];     }      // Traverse the queries     for (int i = 0; i < Query.Count; i++)      {       if (Query[i].first == 1)       {          // Check if L == 1 range         // sum will be A[R-1]         Console.Write(A[(Query[i].second) - 1] + "\n");       }        else        {          // Condition if L > 1 range sum         // will be A[R-1] - A[L-2]         Console.Write(A[(Query[i].second) - 1] -                        A[(Query[i].first) - 2] + "\n");       }     }   }    // Driver Code   public static void Main(String[] args)   {      // Given String     String S = "abcd";      List<pair> Query = new List<pair>();      // Given Queries     Query.Add(new pair(2, 4));     Query.Add(new pair(1, 3));      // Function call     Range_sum_query(S, Query);   } }  // This code is contributed by gauravrajput1 
JavaScript
<script>  // Javascript program for the above approach  // Function to perform range sum queries // on string as per the given condition function Range_sum_query(S, Query) {      // Initialize N by string size     var N = S.length;      // Create array A[] for prefix sum     var A = Array(N);      A[0] = S[0].charCodeAt(0) - 'a'.charCodeAt(0) + 1;      // Iterate till N     for (var i = 1; i < N; i++) {         A[i] = S[i].charCodeAt(0) - 'a'.charCodeAt(0) + 1;         A[i] = A[i] + A[i - 1];     }      // Traverse the queries     for (var i = 0; i < Query.length; i++) {          if (Query[i][0] == 1) {              // Check if L == 1 range             // sum will be A[R-1]             document.write( A[(Query[i][1]) - 1]+ "<br>");         }          else {              // Condition if L > 1 range sum             // will be A[R-1] - A[L-2]             document.write( A[(Query[i][1]) - 1]                         - A[(Query[i][0]) - 2]+ "<br>");         }     } }  // Driver Code // Given string var S = "abcd"; var Query = [];  // Given Queries Query.push([2, 4]); Query.push([1, 3]);  // Function call Range_sum_query(S, Query);  // This code is contributed by itsok. </script>   

Output: 
9 6

 

Time Complexity: O(N), where N is the length of the given string. 
Auxiliary Space: O(N)


Next Article
Reduce string by performing repeated digit sum in group of K

D

divyeshrabadiya07
Improve
Article Tags :
  • Strings
  • Competitive Programming
  • DSA
  • Arrays
  • prefix-sum
  • subarray
  • prefix
  • substring
  • subarray-sum
Practice Tags :
  • Arrays
  • prefix-sum
  • Strings

Similar Reads

  • Range sum queries based on given conditions
    Given an array arr[] of N integers and matrix Queries[][] consisting of Q queries of the form {m, a, b}. For each query the task is to find the sum of array elements according to the following conditions: If m = 1: Find the sum of the array elements in the range [a, b].If m = 2: Rearrange the array
    15+ min read
  • Queries for Sum of Bitwise AND of all Subarrays in a Range
    Given an array arr[] of size N, the task is to answer a set of Q queries, each in the format of queries[i][0] and queries[i][1]. For each queries[i], find the sum of Bitwise AND of all subarrays whose elements lie in the range [queries[i][0], queries[i][1]]. Examples: Input: N = 3, arr[] = {1, 0, 2}
    12 min read
  • Count of Palindromic substrings in an Index range
    Given a string str of small alphabetic characters other than this we will be given many substrings of this string in form of index tuples. We need to find out the count of the palindromic substrings in given substring range. Examples: Input : String str = "xyaabax" Range1 = (3, 5) Range2 = (2, 3) Ou
    11 min read
  • Check if a given string is sum-string
    Given a string of digits, determine whether it is a ‘sum-string’. A string S is called a sum-string if the rightmost substring can be written as the sum of two substrings before it and the same is recursively true for substrings before it. Examples: “12243660” is a sum string. Explanation : 24 + 36
    12 min read
  • Reduce string by performing repeated digit sum in group of K
    Given a string S of length N consisting of digits and an integer K, Reduce the string by performing the following operation till the length of the string is greater than K: Divide the string into consecutive groups of size K such that the first K characters are in the first group, the next K charact
    8 min read
  • Sum of numbers formed by consecutive digits present in a given string
    Given a string S consisting of digits [0 - 9] and lowercase alphabets, the task is to calculate the sum of all numbers represented by continuous sequences of digits present in the string S. Examples: Input: S = "11aa32bbb5"Output: 48Explanation: The consecutive sequence of numbers present in the str
    5 min read
  • Sum of all prefixes of given numeric string
    Given string str having N characters representing an integer, the task is to calculate the sum of all possible prefixes of the given string. Example: Input: str = "1225"Output: 1360Explanation: The prefixes of the given string are 1, 12, 122, and 1225 and their sum will be 1 + 12 + 122 + 1225 = 1360
    8 min read
  • Perform the given queries on the rooted tree
    Given a rooted tree and not necessarily binary. The tree contains N nodes, labeled 1 to N. You are given the tree in the form of an array A[1..N] of size N. A[i] denotes label of the parent of node labeled i. For clarity, you may assume that the tree satisfies the following conditions. The root of t
    14 min read
  • Segment Tree for Range Assignment and Range Sum Queries
    Given an array of size N filled with all 0s, the task is to answer Q queries, where the queries can be one of the two types: Type 1 (1, L, R, X): Assign value X to all elements on the segment from L to R−1, andType 2 (2, L, R): Find the sum on the segment from L to R−1.Examples: Input: N = 5, Q = 3,
    15+ min read
  • Sum of all duck numbers lying in range [L,R] for Q queries
    Given Q queries in the form of a 2D array arr[][] in which every row consists of two numbers L and R which denotes a range [L, R], the task is to find the sum of all duck numbers lying in the given range [L, R]. A duck number is a number that has at least one 0 present in it. Examples: Input: Q = 2,
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences