C program for String Reversal | Samsung

C program for String Reversal | Samsung

Question

Write a C program for String Reversal. Print it in a reverse manner eliminating the repeated characters and spaces.

 

Logic

  • Get the String from the user and reverse the string.
  • Check for the repeated characters using checkRepeat function.
  • If the element is already present skip that character or else store it in new array.
  • If the element is empty space then skip that character.
  • Print the new array.

Program

#include<stdio.h>
#include<string.h>
//C doesn't support bool so we convert int as bool by using typedef
typedef int bool;
#define true 1
#define false 0
bool checkRepeat(char arr[],int find)
{
    int i, len = strlen(arr);
    bool flag = false;
    for(i = 0; i< len ; i++)
    {
        if( find == arr[i])
          {
             flag = true;           //Variable already present in array
             printf("%d",i);
          }

    }
    return flag;
}
int main()
{
    char arr[20],arr2[20], ch;
    bool flag;
    gets(arr);
    //don't use scanf("%s",&arr) cuz it stops when encounter a space
    int i,j,len = strlen(arr);
     j = len-1;
     /*Reversing the string*/
    for(i = 0;i< len/2; i++)
    {
        ch = arr[i];
        arr[i] = arr[j];
        arr[j] = ch;
        j--;
    }
    arr2[0] = arr[0];
    j = 1;
    for(i = 1; i<len; i++)
    {
        if(arr[i] == ' ')
            continue;                   //Skip if space
        flag = checkRepeat(arr2, arr[i]);
        if(!flag)                       //If not a repeating variable
        {
            arr2[j] = arr[i];
            j++;
        }
    }

    printf("\n%s", arr2);
    return 0;

}

Analysis

Time complexity is O(n), here n is the length of the input.

Space complexity is O(n), here n is the length of the input.

You might also like…

To find the next greater element in an array

 

Sree Hari Sanjeev

The founder and CEO of Wisdom Overflow. His enthusiasm and effort has taken the blog to next level. You will be motivated just by taking a look at his daily schedule.