How will you reverse a string

Reversing a string is a simple operation and it is often asked in telephonic interviews or first round of interviews. If input string is 'Hello World' then reversed string will look like 'dlroW olleH'. If the string is stored in an array then the operation is very simple because we just need to swap the characters at two pointers.

Algorithm:
  1. Initialize two pointers one at location 0 and other at length of the string. Let's name them i and j. 
  2. If location of i is less than or equal to location of j then swap the characters at location i and j. 
  3. Increment i counter. 
  4. Decrement j counter. 
  5. Repeat steps 2, 3, 4 till the condition in step 2 is met.

Implementation
reverseString()
{
 String names[] = {"a","b","c","d","e","f"};
 int i=0,j=5;
 String temp;

 while(i<=j)
 {
    temp = names[i];
    names[i] = names[j];
    names[j] = temp;
    i++;
    j--;
 }
}


Complexity: 
The time complexity of this algorithm is O(n) since we have to go through all the locations of the array or string. The space complexity is O(1) since we didn't need additional space for this.

You might also like:
Find White Spaces in Character Array
Find a character in the String
Number is prime or not
Finding Absolute Value
Notes on Sorting and Searching Algorithms
Common String Functions
Product of all array location expect its own
Find a cycle in the Linked List
Find a binomial co-efficient
Remove duplicates from the array
Telephonic phone technical interview questions - Part 2
Counting sort algorithm
B-Tree

No comments:

Post a Comment

NoSQL

This one is reviewed but I need to delete its copy from hubpages or somewhere NoSQL Data models: key-value  Aggregate model.  key or i...