Skip to content
Related Articles

Related Articles

Find characters which when increased by K are present in String

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 08 Sep, 2022
View Discussion
Improve Article
Save Article

Given a string s of lowercase English alphabets and integer K. the task is to check if each character after increasing their ASCII by K is present in the string or not. Return only unique characters and the first index where they are present.

Examples:

Input: s = “dszepvaxuo”, k  = 3
Output: {{1, ‘s’},  {6, ‘a’}, {8, ‘u’}}
Explanation: Moving each character 3 steps gives:
‘d’ -> ‘g’, ‘g’ is not present in s
‘s’ -> ‘v’, ‘v’ is present in s, thus, indices array becomes{{1, ‘s’}}
‘z’ -> ‘c’, ‘c’ is not present in s
‘e’ -> ‘h’, ‘h’ is not present in s
‘p’ -> ‘s’, ‘s’ is present in s, but is already present in indices array
‘v’ -> ‘y’, ‘y’ is not present in s
‘a’ -> ‘d’, ‘d’ is present in s, thus, indices array becomes {{1, ‘s’}. {6, ‘a’}}
‘x’ -> ‘a’, ‘a’ is present in s, but is already present in indices array
‘u’ -> ‘x’, ‘x’ is present in s, thus, indices array becomes {{1, ‘s’}, {6, ‘a’}, {8, ‘u’}}
‘o’ -> ‘r’, ‘r’ is not present in s
Thus, final indices array is {{1, ‘s’},  {6, ‘a’}, {8, ‘u’}}

Input: s = “abcdefg”, k = 2
Output: {{0, ‘a’},  {1, ‘b’},  {4, ‘e’}}

Approach: The approach to solve the problem is as follows:

Store each character in a data structure (like set) for easy look up. Iterate over the string, check for each character if it satisfies the condition and is and add valid character’s indices to the output array if that character is not considered already.

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the characters
// and their indices
vector<pair<int, char> > characters_after_k_steps(int k,
                                                  string s)
{
    // create a set for storing characters
    set<char> st;
    for (int i = 0; i < s.size(); i++) {
        st.insert(s[i]);
    }
 
    // Create a vector to store the final indices
    // and characters as pair
    vector<pair<int, char> > vec;
 
    // Create a visited vector/array  to check
    // if a character has been previously encountered
    // or not
    vector<int> vis(26, 0);
 
    // Iterate through the string, check for each character
    // if after moving k steps ahead new character
    // exists in the string using set.
    // Also check if it has already visited or not
    for (int i = 0; i < s.size(); i++) {
        char ans = char((int(s[i]) + k));
        if (ans >= 'a' && ans <= 'z') {
            if (st.find(ans) != st.end() && !vis[ans - 'a']
                && !vis[s[i] - 'a']) {
                vis[ans - 'a'] = vis[s[i] - 'a'] = 1;
                vec.push_back(make_pair(i, s[i]));
            }
        }
    }
 
    // Return the vector as the answer
    return vec;
}
 
// Driver Code
int main()
{
    string s = "dszepvaxuo";
    int K = 3;
 
    // Function call
    vector<pair<int, char> > ans
        = characters_after_k_steps(K, s);
    for (auto it : ans)
        cout << it.first << " " << it.second << endl;
    return 0;
}


Java




// Java code to implement the approach
import java.io.*;
import java.util.*;
 
class GFG {
 
  static class pair {
    int first;
    char second;
    public pair(int first, char second)
    {
      this.first = first;
      this.second = second;
    }
  }
 
  // Function to find the characters
  // and their indices
  static List<pair> characters_after_k_steps(int k,
                                             String s)
  {
 
    // create a set for storing characters
    Set<Character> st = new HashSet<>();
    for (int i = 0; i < s.length(); i++) {
      st.add(s.charAt(i));
    }
 
    // Create a vector to store the final indices
    // and characters as pair
    List<pair> vec = new ArrayList<>();
 
    // Create a visited vector/array  to check
    // if a character has been previously encountered
    // or not
    boolean[] vis = new boolean[26];
 
    // Iterate through the string, check for each character
    // if after moving k steps ahead new character
    // exists in the string using set.
    // Also check if it has already visited or not
    for (int i = 0; i < s.length(); i++) {
      char ans = (char)((int)s.charAt(i) + k);
      if (ans >= 'a' && ans <= 'z') {
        if (st.contains(ans) && !vis[ans - 'a']
            && !vis[s.charAt(i) - 'a']) {
          vis[ans - 'a'] = vis[s.charAt(i) - 'a']
            = true;
          vec.add(new pair(i, s.charAt(i)));
        }
      }
    }
 
    // Return the vector as the answer
    return vec;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    String s = "dszepvaxuo";
    int K = 3;
 
    // Function call
    List<pair> ans = characters_after_k_steps(K, s);
 
    for (int i = 0; i < ans.size(); i++) {
      pair it = (pair)ans.get(i);
      System.out.println(it.first + " " + it.second);
    }
  }
}
 
// This code is contributed by lokeshmvs21.


Python3




# Python code to implementing the approach
 
# Function to find the charcters
def characters_after_k_steps(k, s):
     
    # Create a set for storing characters
    st = set()
    for i in s:
        st.add(i)
 
    # Create an array to store the final indices
    # and characters as pair
    arr = []
 
    # Create a visited array  to check if a
    # character has been previously encountered or not
    vis = [0 for i in range(26)]
 
    # Iterate through the string, check for each character
    # if after moving k steps ahead new character
    # exists in the string using set.
    # Also check if it has already been visited or not
    for i, x in enumerate(s):
        ans = chr(ord(x) + k)
        if ans >= 'a' and ans <= 'z':
            a = ord(ans) - ord('a')
            b = ord(x) - ord('a')
            if (ans in st) and vis[a] == 0 and vis[b] == 0:
                vis[a] = 1
                vis[b] = 1
                arr.append([i, x])
 
    # Return the resultant array
    return arr
 
 
# Driver Code
if __name__ == "__main__":
    s = "dszepvaxuo"
    k = 3
    ans = characters_after_k_steps(k, s)
    for i in ans:
        print(i[0], i[1])


C#




// C# code to implement the approach
using System;
using System.Collections.Generic;
 
public class GFG {
 
  class pair {
    public int first;
    public char second;
    public pair(int first, char second)
    {
      this.first = first;
      this.second = second;
    }
  }
 
  // Function to find the characters
  // and their indices
  static List<pair> characters_after_k_steps(int k,
                                             String s)
  {
 
    // create a set for storing characters
    HashSet<char> st = new HashSet<char>();
    for (int i = 0; i < s.Length; i++) {
      st.Add(s[i]);
    }
 
    // Create a vector to store the readonly indices
    // and characters as pair
    List<pair> vec = new List<pair>();
 
    // Create a visited vector/array  to check
    // if a character has been previously encountered
    // or not
    bool[] vis = new bool[26];
 
    // Iterate through the string, check for each character
    // if after moving k steps ahead new character
    // exists in the string using set.
    // Also check if it has already visited or not
    for (int i = 0; i < s.Length; i++) {
      char ans = (char)((int)s[i] + k);
      if (ans >= 'a' && ans <= 'z') {
        if (st.Contains(ans) && !vis[ans - 'a']
            && !vis[s[i] - 'a']) {
          vis[ans - 'a'] = vis[s[i] - 'a']
            = true;
          vec.Add(new pair(i, s[i]));
        }
      }
    }
 
    // Return the vector as the answer
    return vec;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    String s = "dszepvaxuo";
    int K = 3;
 
    // Function call
    List<pair> ans = characters_after_k_steps(K, s);
 
    for (int i = 0; i < ans.Count; i++) {
      pair it = (pair)ans[i];
      Console.WriteLine(it.first + " " + it.second);
    }
  }
}
 
// This code contributed by shikhasingrajput


Javascript




<script>
// Javascript code to implement the approach
 
// Function to find the characters
// and their indices
function characters_after_k_steps(k, s)
{
 
    // create a set for storing characters
    let st = new Set();
    for (let i = 0; i < s.length; i++) {
        st.add(s[i]);
    }
 
    // Create a vector to store the final indices
    // and characters as pair
    let vec = [];
 
    // Create a visited vector/array  to check
    // if a character has been previously encountered
    // or not
    let vis = new Array(26).fill(0);
 
    // Iterate through the string, check for each character
    // if after moving k steps ahead new character
    // exists in the string using set.
    // Also check if it has already visited or not
    for (let i = 0; i < s.length; i++) {
        let ans = String.fromCharCode(s[i].charCodeAt(0) + k);
        if (ans >= 'a' && ans <= 'z') {
            if (st.has(ans) && !vis[ans.charCodeAt(0) - 'a'.charCodeAt(0)]
                && !vis[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]) {
                vis[ans.charCodeAt(0) - 'a'.charCodeAt(0)] = vis[s[i].charCodeAt(0) - 'a'.charCodeAt(0)] = 1;
                vec.push([i, s[i]]);
            }
        }
    }
 
    // Return the vector as the answer
    return vec;
}
 
// Driver Code
 
let s = "dszepvaxuo";
let K = 3;
 
// Function call
let ans = characters_after_k_steps(K, s);
for (let it of ans)
    document.write(it[0] + " " + it[1] + "<br>");
 
// This code is contributed by saurabh_jaiswal.
</script>


Output

1 s
6 a
8 u

Time complexity: O(N * log(N))
Auxiliary Space: O(N) 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!