Long Pressed Name in C++

C++Server Side ProgrammingProgramming

Suppose a man is typing some name on keyboard. Sometimes some buttons are long-pressed by mistake. So it may type one or more extra character. So we will take two strings, and check whether the second string is long-pressed name or not. So if the name is “Amit”, and second string is “Ammittt” is longpressed name. But “Ammttt” is not, because character i is not present here.

To solve this, we will follow these steps −

  • let j := 0
  • for i := 0, i < second.size, increase i by 1 −
    • if j < actual_name.size and actual_name[j] = second[i], thenincrease j by 1
  • return true when j = actual_name.size, otherwise false


Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   bool isLongPressedName(string name, string typed) {
      int j = 0;
      for(int i = 0; i < typed.size(); i++){
         if(j < name.size() && name[j] == typed[i])j++;
      return j == name.size();
   Solution ob;
   string res = ob.isLongPressedName("Amit", "Ammittt") ? "true" :
      cout << res;




Published on 16-Jan-2020 16:08:32