Alternating Characters

  • + 20 comments

    Anybody pass all 12 test case? I pass form 1 to 8, but cannot pass from 9: "# 9 3s : Terminated due to timeout." I copy source code to VS and run that test case, It run perfect. My Alg is O(n), do you have any alg better?

    • + 2 comments

      I have the same problem. Locally I am able to run all test cases and they produce correct answers within seconds, but here they get terminated due to timeout.

      • + 6 comments

        Silly me, I've made a mistake of actually deleting from strings, when all I had to do is count the number of delete operations needed. Once the code was changed to ONLY COUNT, additional test cases were passed easily.

        • + 1 comment

          Thanks

          • + 3 comments

            int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */

            int n;
            cin>>n;
            for(int j = 0; j< n; j++){
            
            string s;
            cin>>s;
            int del = 0;
            for(int i = 1; i< s.length(); i++)
                {
                if(s[i] == s[i-1])
                    del++;
            }
                cout<<del<<endl;
            }
            return 0;
            

            }

            • + 3 comments

              YOUR CODE IS NOT CLEARING ALL THE TEST CASES,,,,,!!!

              • + 0 comments

                exactly. you need to keep track at least of a "pivot" char, the last valid one from the previous iteration...

              • + 0 comments

                int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */
                int t; cin >> t; string str;

                while(t) {
                    cin >> str;
                
                    int i=0, count = 0;
                    while(i < static_cast<int>(str.size()-1))
                        {
                        if(i>=0 && str[i] == str[i+1])
                            {
                            str.erase(i,1);
                            count++;
                         //   cout << str.size()-1 << "      ";
                            i--;
                        } else {
                            i++;
                        }
                    }
                   cout << count << "\n";
                    t--;
                }
                return 0;
                

                }

              • + 0 comments

                IT's passing all the test cases . Please check again .

            • + 0 comments

              should be length -1 in loop !

            • + 0 comments

              program outputs wrong answer when cin is replaced by getline(cin,s)

        • + 0 comments

          tru story, bro... ))))))

        • + 0 comments

          Thanks, I made the same mistake. Got it fixed :D

        • + 0 comments

          very true!...i wasted 5 hackos for getting the test case, just had to count!...no manipulation of string required, it simply wastes time!...thanks

        • + 0 comments

          Thanks! That was the problem that was failing the test cases due to timeout issue.

        • + 0 comments

          Same mistake bro thanks.

      • + 3 comments

        Here is the simplest solution (passes all 12 cases ):

        public static void main(String[] args) {
             ...
        
                for (String input : inputs) {
        
                    int noOfDeletions = 0;
                    char[] chars = input.toCharArray();
                    for (int i = 0; i < chars.length; i++) {
                        char currChar = chars[i];
                        char nextChar = i + 1 == chars.length ? 'c' : chars[i + 1];
        
                        if (currChar == nextChar) {
                            noOfDeletions++;
                        }
                    }
                    System.out.println(noOfDeletions);
                }
            }
        
        • + 0 comments

          Calling this inside the for loop that accepts the Strings worked for me.

          static void counter(String str1){
              int count=0;
              int j=1;
              char[] ar = str1.toCharArray();
              for(int i=0;i<ar.length-1;i++){
                  if(ar[i]== ar[j] && j<ar.length){
                      count++;
                  }
          
                  j++;
              }
              System.out.println(count);
          }
          
        • + 0 comments

          for (String input : inputs) i think here there is mistake by using the symbol :

        • + 0 comments

          Adding 'c' char to the end is an ugly workaround; the loop should end at (chars.length - 1) instead. Then the currChar will have values from 0 to length - 1 and nextChar from 1 to length.

    • + 3 comments

      yes I passed all 12. My Alg is also O(n). So what is the problem you are facing? And what language you are using. You can check my solution as well and let me know where I can see your solution.

      • + 1 comment

        how many seconds did the most expensive test take? Me I'm around 0.03s...

        • + 1 comment

          my most expensive test takes 0.35s.Did you find a better way to improve your code?

          • + 0 comments

            Testcase #10, #11. 0.31 seconds. Are you using Java?

    • + 1 comment

      Yep - I did. Mine is O(n) too but I don't think you can do better than that as you'll need to go through the string at least once.

      • + 2 comments

        we can do better, may be input will repeat so for that not need to calculate again just show older result :)

        • + 0 comments

          It'll be hard to show the equality in less than linear time :)

        • + 0 comments

          Besides the fact that string comparison is obviously linear, you would still have to have a fallback to a O(n) algorithm. Since for an input tending to infinity you would need to use it, the whole algorithm would still be O(n).

    • + 2 comments

      The better solution is O(n/2). If your program is not optimed, then it "MAY" thow "Timeout" as it exceeds the maximum time limit.

      • + 1 comment

        How will you do O(n/2), you still need to go though each character to see if it matches the previous one or not.

        • + 5 comments

          https://codepair.hackerrank.com/paper/WV5eMmhM?b=eyJyb2xlIjoiY2FuZGlkYXRlIiwibmFtZSI6InJhdmlyb3NoYW4iLCJlbWFpbCI6InJhdmlyb3NoYW4udGFsa0BnbWFpbC5jb20ifQ%3D%3D

          public class Solution { public static void main(String[] args) {

               // System.out.println("Starting the program");
              try {
                  BufferedReader br = new BufferedReader(new InputStreamReader(
                          System.in));
          
                  String input;
                  input=br.readLine();
                  int T=Integer.parseInt(input);
                  String[] inputArray = new String[T];
                  for (int i = 0; i < T; i++) {
                      inputArray[i]=br.readLine();
                  }
          
                  //System.out.println("==========================");
          
                  for (String string : inputArray) {
                      int size=string.length();
                      int counter=0;
                      int i,j;
                      for (i = 0, j=size-1; i+1 <j-1; i++,j--) {
                          if(string.charAt(i)==string.charAt(i+1)){
                              counter++;
                          }
                          if(string.charAt(j)==string.charAt(j-1)){
                              counter++;
                          }
                      }
          
                      if(size%2==0){
                          if(string.charAt(i)==string.charAt(j)){
                              counter++;
                          }
                      }
                      else{
                          if(string.charAt(i)==string.charAt(i+1)){
                              counter++;
                          }
                          if(string.charAt(i+1)==string.charAt(j)){
                              counter++;
                          }
                      }
          
                      System.out.println(counter);
                  }
          
              } catch (Exception io) {
                  io.printStackTrace();
              }
              // System.out.println("Ending the program");
          }
          

          }

          • + 1 comment

            Nice. Thanks for sharing.

            • + 4 comments

              Scanner in =new Scanner(System.in); int n=in.nextInt();

                  for(int i=0; i<n; i++)
                      { int count=0;
                      String s=in.next();
                      int l=s.length();
                      for(int j=0; j<l-1;j++)
                          {
                          if(s.charAt(j)==s.charAt(j+1))
                              {
              
                              count++;
              
                          }
                      }
                      System.out.println(count);
                  }
              
              • + 0 comments

                No actual deleteions, awesome!

              • + 0 comments

                Thanks it helped very much..:)

              • + 0 comments

                Your code works but if one of the testcases were something like 'abba' it wouldnt work!!!!

              • + 0 comments

                Brilliant..

          • + 0 comments

            First, O(N) is the same as O(N/2). The "O" means "order of", meaning that we ignore the coefficients to the terms (be they polynomial, log, or exponential).

            Second, this algorithm is no more efficient than the trivial one. It's also considerably less clear.

            While it's true you loop half the number of times, you do two comparisons each time through the loop. So, every character is examined twice (except the ones on the ends).

            Those who are timing out are doing something very inefficient, and are not O(N).

            Westerngravity has the right idea.

          • + 0 comments

            @ravisohan, a simple java solution would be this:

            public class Solution {
                public static int countDeletions(String s) {
                    int count = 0, index=0;
                    for(int i=1;i<s.length();i++){
                        if(s.charAt(i) == s.charAt(index)) {
                            count++;
                        } else {
                            index = i;
                        }
                    }
                    return count;
                }
            
                public static void main(String[] args) {
                    Scanner in = new Scanner(System.in);
                    int t = Integer.parseInt(in.nextLine());
                    String[] input = new String[t];
                    for(int i=0;i<t;i++){
                        input[i] = in.nextLine();
                    }
                    for(int i=0;i<t;i++){
                        System.out.println(countDeletions(input[i]));
                    }
                }
            }
            

            It passes all the test cases :)

          • + 0 comments

            This my friend, is not O(n/2). Think of it this way, you are reading al lthe elements in the data set. That is what determines O(). The style of looping is not really a determining factor.

            Moreover, O(N/2) is simply O(0.5N) and that is ignored. This notation does not care about the constant. So, a complexity of O(N) and O(10^4N) and O(0.0003N) is all the same- O(N).

          • + 0 comments

            Here I have a simpler solution although I don't think its all that elegant but passed all cases.

            public static void main(String[] args) {
            
                Scanner sc = new Scanner(System.in);
                int T = sc.nextInt();       
            
                for(int j=0;j < T;j++) {
                    String N = sc.next();
                    StringBuilder n = new StringBuilder(N);            
                    int dels = 0;
                    String tmp = "";
            
                    for(int i=0;i < n.length();i++) {
                        if(i==0) {
                            tmp = String.valueOf(n.charAt(i));
                        } else if(i != 0 && n.charAt(i) != n.charAt(i-1)) {
                            tmp = tmp.concat(String.valueOf(n.charAt(i)));
            
                        } else { dels++; }             
                    }
            
                    System.out.print(dels +"\n"); 
                }
            }
            
      • + 0 comments

        O(n/2) is the same than O(n)

    • + 0 comments

      Yes. I have passed all the test cases.

    • + 0 comments

      Passed, with C++.

    • + 0 comments

      include

      include

      include

      include

      int main() {

      /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
      char str[100000];
      long int len;
      int t, i, j,dcount;
      scanf("%d", &t);
      while(t--){
      scanf("%s", str);
      len = strlen(str);
      dcount = 0;
          i=0;j=1;
          while(j<len){
          if(str[i]==str[j]){
          dcount++;
              j++;
          }
              else{
                  i=j;
                  j++;
              }
          }
      
          printf("%d\n", dcount);
      }
      return 0;
      

      }

    • + 1 comment

      Hey !! even i had the same problem !! I was using java. When i changed my string from Sring class to StringBuffer... it worked.

      I know that the reply is 8months late.. :P :P But it may be helpful for others.

      • + 0 comments

        i did almost the same thing, im getting timeout for test cases 8-12?

    • + 0 comments

      yeah . Mine is O(n).

      try and analyze this. I'm giving you the source code.

      include

      include

      include

      include

      int main() { int i,j,c=0,x,k; char a[100]; scanf("%d",&i);

      while(i--)
          { c=0;            //refreshing the counter
         scanf("%s",a);
          x=strlen(a);       //length of string
          for(j=0;j!=x-1;j++)   //no need to traverse till end                                 //but end-1
              {
      
              if(a[j] ==a[j+1])     //calc. those which are same
                {  c++;
      
                }
      
          }
          printf("%d\n",c);
      
      }
      
      return 0;
      

      }

    • + 0 comments

      oh my god,is that string consist of the letter only 'A' or 'B'?If you care it,you will fail to pass additional case.That's a bug.

    • + 0 comments

      oh my god,is that string consist of the letter only 'A' or 'B'?If you care it,you will fail to pass additional case.That's a bug.

    • + 0 comments

      number = int(raw_input()) for k in range(1,number+1): string = raw_input().strip() i = len(string) -1 # scan for two consecutive del_count = 0 #characters, if found increase while i >0: #delete count if string[i] == string[i-1]: del_count = del_count+1 i = i-1

      print del_count
      
    • + 0 comments

      number = int(raw_input()) for k in range(1,number+1): string = raw_input().strip() i = len(string) -1 # scan for two consecutive del_count = 0 #characters, if found increase while i >0: #delete count if string[i] == string[i-1]: del_count = del_count+1 i = i-1

      print del_count
      
    • + 0 comments

      i was concatenating the strings for testing purpose and that happened. The I delete those lines and passed all the test cases

    • + 1 comment

      Scanner in =new Scanner(System.in); int n=in.nextInt();

          for(int i=0; i<n; i++)
              { int count=0;
              String s=in.next();
              int l=s.length();
              for(int j=0; j<l-1;j++)
                  {
                  if(s.charAt(j)==s.charAt(j+1))
                      {
      
                      count++;
      
                  }
              }
              System.out.println(count);
          }
      
      • + 0 comments

        It's not working for me ...

    • + 1 comment

      This will work time complexity O(N) Auxiliary Space O(N)

      import java.io.; import java.util.; import java.text.; import java.math.; import java.util.regex.*;

      public class Solution {

      public static void main(String[] args) {
          Scanner sc = new Scanner(System.in);
          int t = sc.nextInt();
          sc.nextLine();
          for(;t>0;t--){
              StringBuffer a = new  StringBuffer(sc.nextLine());
              StringBuffer b = new  StringBuffer("");
              b.append(a.charAt(0));
              for(int i=1; i<a.length();i++){
                  if(b.charAt(b.length()-1)!=a.charAt(i))b.append(a.charAt(i));
              }
              System.out.println(a.length()-b.length());
          }
      }
      

      }

      • + 0 comments
        static void counter(String str1){
            int count=0;
            int j=1;
            char[] ar = str1.toCharArray();
            for(int i=0;i<ar.length-1;i++){
                if(ar[i]== ar[j] && j<ar.length){
                    count++;
                }
        
                j++;
            }
            System.out.println(count);
        }
        
    • + 0 comments

      public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner in = new Scanner(System.in); int n = in.nextInt(); for(int i=0;i

    • + 0 comments
      function alternatingCharacters(s){
          let count = 0;
          for(x in s){
              if(s[x] === s[parseInt(x)+1]){
                  count++;
              }
          }
          return count;
      }
      

      Here is mine! passed all test cases.

    • + 0 comments
      // Complete the alternatingCharacters function below.
      static int alternatingCharacters(String s) {
          StringBuilder sb = new StringBuilder(s);
          int deletion=0;
          int i=0;
          while(!isAlternateCharacter(sb)) {
              if(sb.charAt(i)==sb.charAt(i+1)){
                  sb.deleteCharAt(i+1);
                  deletion++;
                  i=0;
              } else {
                  i++;
              }
      
          }
          return deletion;
      }
      
      static boolean isAlternateCharacter(StringBuilder str) {
          for(int i=0;i<str.length()-1;i++) {
              if(str.charAt(i)==str.charAt(i+1)) {
                  return false;
              }
          }
          return true;
      }