The Wayback Machine - https://web.archive.org/web/20240930175346/https://www.geeksforgeeks.org/stack-set-3-reverse-string-using-stack/
Open In App

How to Reverse a String using Stack

Last Updated : 23 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Easy
76.17%
99K

Given a string, reverse it using stack. 

Example:

Input: str = “GeeksQuiz”
Output: ziuQskeeG

Input: str = “abc”
Output: cba

Recommended Practice

Approach:

The idea is to create an empty stack and push all the characters from the string into it. Then pop each character one by one from the stack and put them back into the input string starting from the 0’th index. As we all know, stacks work on the principle of first in, last out. After popping all the elements and placing them back to string, the formed string would be reversed.

Follow the steps given below to reverse a string using stack. 

  • Create an empty stack.
  • One by one push all characters of string to stack.
  • One by one pop all characters from stack and put them back to string.

Below is the implementation of the above approach:

C++




// C++ program to reverse a string using stack
#include <bits/stdc++.h>
using namespace std;
 
// A structure to represent a stack
class Stack {
public:
    int top;
    unsigned capacity;
    char* array;
};
 
// function to create a stack of given
// capacity. It initializes size of stack as 0
Stack* createStack(unsigned capacity)
{
    Stack* stack = new Stack();
    stack->capacity = capacity;
    stack->top = -1;
    stack->array
        = new char[(stack->capacity * sizeof(char))];
    return stack;
}
 
// Stack is full when top is equal to the last index
int isFull(Stack* stack)
{
    return stack->top == stack->capacity - 1;
}
 
// Stack is empty when top is equal to -1
int isEmpty(Stack* stack) { return stack->top == -1; }
 
// Function to add an item to stack.
// It increases top by 1
void push(Stack* stack, char item)
{
    if (isFull(stack))
        return;
    stack->array[++stack->top] = item;
}
 
// Function to remove an item from stack.
// It decreases top by 1
char pop(Stack* stack)
{
    if (isEmpty(stack))
        return -1;
    return stack->array[stack->top--];
}
 
// A stack based function to reverse a string
void reverse(char str[])
{
    // Create a stack of capacity
    // equal to length of string
    int n = strlen(str);
    Stack* stack = createStack(n);
 
    // Push all characters of string to stack
    int i;
    for (i = 0; i < n; i++)
        push(stack, str[i]);
 
    // Pop all characters of string and
    // put them back to str
    for (i = 0; i < n; i++)
        str[i] = pop(stack);
}
 
// Driver code
int main()
{
    char str[] = "GeeksQuiz";
 
    reverse(str);
    cout << "Reversed string is " << str;
 
    return 0;
}
 
// This code is contributed by rathbhupendra


C




// C program to reverse a string using stack
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
// A structure to represent a stack
struct Stack {
    int top;
    unsigned capacity;
    char* array;
};
 
// function to create a stack of given
// capacity. It initializes size of stack as 0
struct Stack* createStack(unsigned capacity)
{
    struct Stack* stack
        = (struct Stack*)malloc(sizeof(struct Stack));
    stack->capacity = capacity;
    stack->top = -1;
    stack->array
        = (char*)malloc(stack->capacity * sizeof(char));
    return stack;
}
 
// Stack is full when top is equal to the last index
int isFull(struct Stack* stack)
{
    return stack->top == stack->capacity - 1;
}
 
// Stack is empty when top is equal to -1
int isEmpty(struct Stack* stack)
{
    return stack->top == -1;
}
 
// Function to add an item to stack.
// It increases top by 1
void push(struct Stack* stack, char item)
{
    if (isFull(stack))
        return;
    stack->array[++stack->top] = item;
}
 
// Function to remove an item from stack.
// It decreases top by 1
char pop(struct Stack* stack)
{
    if (isEmpty(stack))
        return INT_MIN;
    return stack->array[stack->top--];
}
 
// A stack based function to reverse a string
void reverse(char str[])
{
    // Create a stack of capacity
    // equal to length of string
    int n = strlen(str);
    struct Stack* stack = createStack(n);
 
    // Push all characters of string to stack
    int i;
    for (i = 0; i < n; i++)
        push(stack, str[i]);
 
    // Pop all characters of string and
    // put them back to str
    for (i = 0; i < n; i++)
        str[i] = pop(stack);
}
 
// Driver program to test above functions
int main()
{
    char str[] = "GeeksQuiz";
 
    reverse(str);
    printf("Reversed string is %s", str);
 
    return 0;
}


Java




/* Java program to reverse
String using Stack */
 
import java.util.*;
 
// stack
class Stack {
    int size;
    int top;
    char[] a;
 
    // function to check if stack is empty
    boolean isEmpty() { return (top < 0); }
 
    Stack(int n)
    {
        top = -1;
        size = n;
        a = new char[size];
    }
 
    // function to push element in Stack
    boolean push(char x)
    {
        if (top >= size) {
            System.out.println("Stack Overflow");
            return false;
        }
        else {
            a[++top] = x;
            return true;
        }
    }
 
    // function to pop element from stack
    char pop()
    {
        if (top < 0) {
            System.out.println("Stack Underflow");
            return 0;
        }
        else {
            char x = a[top--];
            return x;
        }
    }
}
 
// Driver code
class Main {
    // function to reverse the string
    public static void reverse(StringBuffer str)
    {
        // Create a stack of capacity
        // equal to length of string
        int n = str.length();
        Stack obj = new Stack(n);
 
        // Push all characters of string
        // to stack
        int i;
        for (i = 0; i < n; i++)
            obj.push(str.charAt(i));
 
        // Pop all characters of string
        // and put them back to str
        for (i = 0; i < n; i++) {
            char ch = obj.pop();
            str.setCharAt(i, ch);
        }
    }
 
    // driver function
    public static void main(String args[])
    {
        // create a new string
        StringBuffer s = new StringBuffer("GeeksQuiz");
 
        // call reverse method
        reverse(s);
 
        // print the reversed string
        System.out.println("Reversed string is " + s);
    }
}


Python3




# Python program to reverse a string using stack
 
# Function to create an empty stack.
# It initializes size of stack as 0
 
 
def createStack():
    stack = []
    return stack
 
# Function to determine the size of the stack
 
 
def size(stack):
    return len(stack)
 
# Stack is empty if the size is 0
 
 
def isEmpty(stack):
    if size(stack) == 0:
        return true
 
# Function to add an item to stack .
# It increases size by 1
 
 
def push(stack, item):
    stack.append(item)
 
# Function to remove an item from stack.
# It decreases size by 1
 
 
def pop(stack):
    if isEmpty(stack):
        return
    return stack.pop()
 
# A stack based function to reverse a string
 
 
def reverse(string):
    n = len(string)
 
    # Create a empty stack
    stack = createStack()
 
    # Push all characters of string to stack
    for i in range(0, n, 1):
        push(stack, string[i])
 
    # Making the string empty since all
    # characters are saved in stack
    string = ""
 
    # Pop all characters of string and
    # put them back to string
    for i in range(0, n, 1):
        string += pop(stack)
 
    return string
 
 
# Driver program to test above functions
string = "GeeksQuiz"
string = reverse(string)
print("Reversed string is " + string)
 
# This code is contributed by Sunny Karira


C#




/* C# program to reverse
String using Stack */
using System;
using System.Text;
// stack
class Stack {
    public int size;
    public int top;
    public char[] a;
 
    // function to check if stack is empty
    public Boolean isEmpty() { return (top < 0); }
 
    public Stack(int n)
    {
        top = -1;
        size = n;
        a = new char[size];
    }
 
    // function to push element in Stack
    public Boolean push(char x)
    {
        if (top >= size) {
            Console.WriteLine("Stack Overflow");
            return false;
        }
        else {
            a[++top] = x;
            return true;
        }
    }
 
    // function to pop element from stack
    public char pop()
    {
        if (top < 0) {
            Console.WriteLine("Stack Underflow");
            return ' ';
        }
        else {
            char x = a[top--];
            return x;
        }
    }
}
 
class GFG {
    // function to reverse the string
    public static void reverse(StringBuilder str)
    {
        // Create a stack of capacity
        // equal to length of string
        int n = str.Length;
        Stack obj = new Stack(n);
 
        // Push all characters of string
        // to stack
        int i;
        for (i = 0; i < n; i++)
            obj.push(str[i]);
 
        // Pop all characters of string
        // and put them back to str
        for (i = 0; i < n; i++) {
            char ch = obj.pop();
            str[i] = ch;
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        // create a new string
        StringBuilder s = new StringBuilder("GeeksQuiz");
 
        // call reverse method
        reverse(s);
 
        // print the reversed string
        Console.WriteLine("Reversed string is " + s);
    }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// Javascript program to reverse
// String using Stack
 
// stack
class Stack
{
    size;
    top;
    a = [];
  
    // Function to check if stack is empty
    isEmpty()
    {
        return(this.top < 0);
    }
     
    constructor(n)
    {
        this.top = -1;
        this.size = n;
        this.a = new Array(this.size);
    }
  
    // Function to push element in Stack
    push(x)
    {
        if (this.top >= this.size)
        {
            document.write("Stack Overflow<br>");
            return false;
        }
        else
        {
            this.a[++this.top] = x;
            return true;
        }
    }
  
    // Function to pop element from stack
    pop()
    {
        if (this.top < 0)
        {
            document.write("Stack Underflow<br>");
            return 0;
        }
        else
        {
            let x = this.a[this.top--];
            return x;
        }
    }
}
 
// Function to reverse the string
function reverse(str)
{
     
    // Create a stack of capacity
    // equal to length of string
    let n = str.length;
    let obj = new Stack(n);
      
    // Push all characters of string
    // to stack
    let i;
    for(i = 0; i < n; i++)
        obj.push(str[i]);
  
    // Pop all characters of string
    // and put them back to str
    for(i = 0; i < n; i++)
    {
        let ch = obj.pop();
        str[i] = ch;
    }
}
 
// Driver Code
let s = "GeeksQuiz".split("");
 
// Call reverse method
reverse(s);
 
// Print the reversed string
document.write("Reversed string is " +
               s.join(""));
 
// This code is contributed by rag2127
 
</script>


Output

Reversed string is ziuQskeeG

Time Complexity: O(N)  
Auxiliary Space: O(N) for Stack.

 Reversing The String become Easy If You Use Stack InBulid  liberay (STL).

  Here in this approach we have use stack(stl) Which is LIFO type DataStructure.

C++




#include <bits/stdc++.h>
#include<iostream>
#include<string>
#include<stack>
using namespace std;
 
//passing str by reference because be need to do changes in str
//only not want to create any copy and when return it.
void the_helper(string &str;){
  //stack which takw char input.
  stack<char>s;
  //we push all char in stack.
  for(auto it:str)s.push(it);
  //here we clear all char present in str.
  str.clear();
  // as stack is LIFO DS we push_back all char and our string is reverse now.
  while(!s.empty()){
    str.push_back(s.top());
    s.pop();
  }
}
int main() {
  //string we want to reverse.
  string str = "GeeksQuiz";
  //the function that make all necessary changes.
  the_helper(str);
  //finally return/output the reverse string
  cout << "Reversed string is : " << str;
  return 0;
}


Python3




# import the required module
import string
 
# define a function to reverse a string
def the_helper(s):
    # create an empty stack
    stack = []
    # push all characters of the string into the stack
    for i in s:
        stack.append(i)
    # empty the string
    s = ""
    # pop all characters from the stack and append to the string
    while stack:
        s += stack.pop()
    # return the reversed string
    return s
 
# main function
if __name__ == "__main__":
    # define the input string
    str = "GeeksQuiz"
     
    # call the function to reverse the string
    reversed_str = the_helper(str)
     
    # print the reversed string
    print("Reversed string is: ", reversed_str)


C#




/// c#
using System;
using System.Collections.Generic;
 
public class GFG {
    static void the_helper(ref string str) {
        //stack which takes char input.
        Stack<char> s = new Stack<char>();
        //we push all char in stack.
        foreach (char ch in str) {
            s.Push(ch);
        }
        //here we clear all char present in str.
        str = "";
        //as stack is LIFO DS we push_back all char and our string is reverse now.
        while (s.Count != 0) {
            str += s.Peek();
            s.Pop();
        }
    }
 
    static void Main() {
        //string we want to reverse.
        string str = "GeeksQuiz";
        //the function that makes all necessary changes.
        the_helper(ref str);
        //finally return/output the reverse string
        Console.WriteLine("Reversed string is : " + str);
    }
}
 
// ksam24000


Javascript




// passing str by reference because be need to do changes in str
// only not want to create any copy and when return it.
function the_helper(str)
{
 
// stack which takw char input.
  let s = [];
   
  // we push all char in stack.
  for (let i = 0; i < str.length; i++) {
    s.push(str.charAt(i));
  }
   
  // here we clear all char present in str.
  str = '';
   
  // as stack is LIFO DS we push_back all char and our string is reverse now.
  while (s.length > 0) {
    str += s.pop();
  }
 
  return str;
}
 
// string we want to reverse.
let str = 'GeeksQuiz';
 
// the function that make all necessary changes.
str = the_helper(str);
 
  // finally return/output the reverse string
console.log('Reversed string is: ' + str);


Java




import java.util.*;
 
public class Main {
//passing str by reference because be need to do changes in str
//only not want to create any copy and when return it.
static void the_helper(StringBuilder str){
//stack which takes char input.
Stack<Character> s = new Stack<>();
//we push all char in stack.
for(int i=0;i<str.length();i++) s.push(str.charAt(i));
//here we clear all char present in str.
str.delete(0, str.length());
// as stack is LIFO DS we append all char and our string is reverse now.
while(!s.empty()){
str.append(s.peek());
s.pop();
}
}
public static void main(String[] args) {
//string we want to reverse.
StringBuilder str = new StringBuilder("GeeksQuiz");
//the function that make all necessary changes.
the_helper(str);
//finally return/output the reverse string
System.out.println("Reversed string is : " + str);
}
}


Output

Reversed string is : ziuQskeeG

Time Complexity: O(N)  Only one traversal to push and pop so O(n)+O(n)==O(n).
Auxiliary Space: O(N) Extra for Stack.

For other methods, please refer reverse a string.



Previous Article
Next Article

Similar Reads

Reverse the Words of a String using Stack
Given string str consisting of multiple words, the task is to reverse the entire string word by word.Examples: Input: str = "I Love To Code" Output: Code To Love IInput: str = "data structures and algorithms" Output: algorithms and structures data Approach: This problem can be solved not only with the help of the strtok() but also it can be solved
8 min read
Print Reverse a linked list using Stack
Given a linked list, print the reverse of it without modifying the list. Examples: Input : 1 2 3 4 5 6 Output : 6 5 4 3 2 1 Input : 12 23 34 45 56 67 78 Output : 78 67 56 45 34 23 12 Below are different solutions that are now allowed here as we cannot use extra space and modify the list. Recursive solution to print reverse a linked list. Requires e
9 min read
Reverse alternate levels of a perfect binary tree using Stack
Given a Perfect Binary Tree, the task is to reverse the alternate level nodes of the binary tree.Examples: Input: a / \ b c / \ / \ d e f g / \ / \ / \ / \ h i j k l m n o Output: Inorder Traversal of given tree h d i b j e k a l f m c n g o Inorder Traversal of modified tree o d n c m e l a k f j b i g h Input: a / \ b c Output: Inorder Traversal
10 min read
Reverse an array using Stack
Given an array arr[] of size N, the task to reverse the array using Stack. Examples: Input: arr[] = { 10, 20, 30, 40, 50 } Output: 50 40 30 20 10 Explanation: Reversing the array modifies arr[] to { 50, 40, 30, 20, 10 } Therefore, the required output is 50 40 30 20 10. Input: arr[] = { 1 } Output: 1 Iterative and Recursive Approach: Refer the artic
12 min read
Reverse a Stack using Queue
Given a stack, the task is to reverse the stack using the queue data structure. Examples: Input: Stack: (Top to Bottom) [10 -> 20 -> 30 -> 40]Output: Stack: (Top to Bottom) [40 -> 30 -> 20 -> 10] Input: Stack: [6 -> 5 -> 4]Output: Stack: [4 -> 5 -> 6] Approach: The problem can be solved based on the following idea: The
5 min read
How to Reverse a Stack using Recursion
Write a program to reverse a stack using recursion, without using any loop. Example: Input: elements present in stack from top to bottom 1 2 3 4 Output: 4 3 2 1 Input: elements present in stack from top to bottom 1 2 3Output: 3 2 1 Recommended PracticeReverse a StackTry It!Reverse a stack using RecursionThe idea of the solution is to hold all value
11 min read
Reverse a stack without using extra space in O(n)
Reverse a Stack without using recursion and extra space. Even the functional Stack is not allowed. Examples: Input : 1->2->3->4 Output : 4->3->2->1 Input : 6->5->4 Output : 4->5->6 We have discussed a way of reversing a stack in the below post.Reverse a Stack using Recursion The above solution requires O(n) extra space
6 min read
Reverse a number using stack
Given a number , write a program to reverse this number using stack. Examples: Input : 365Output : 563Input : 6899Output : 9986We have already discussed the simple method to reverse a number in this post. In this post we will discuss about how to reverse a number using stack.The idea to do this is to extract digits of the number and push the digits
5 min read
Reverse a Linked List in groups of given size using Stack
Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL, k = 2 Output: head: 2 -> 1 -
8 min read
Sort a stack using a temporary stack
Given a stack of integers, sort it in ascending order using another temporary stack. Examples: Input : [34, 3, 31, 98, 92, 23] Output : [3, 23, 31, 34, 92, 98] Input : [3, 5, 1, 4, 2, 8] Output : [1, 2, 3, 4, 5, 8] Recommended PracticeSort a stackTry It! Algorithm: Create a temporary stack say tmpStack.While input stack is NOT empty do this: Pop an
6 min read
Find maximum in stack in O(1) without using additional stack in Python
The task is to design a stack which can get the maximum value in the stack in O(1) time without using an additional stack in Python. Examples: Input: Consider the following SpecialStack 16 –> TOP29151918When getMax() is called it should return 29, which is the maximum element in the current stack. If we do pop two times on stack, the stack becom
3 min read
Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is the same as the sum of reverse(arr[i]) and arr[j]. Examples: Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 min read
Python program to reverse a stack
The stack is a linear data structure which works on the LIFO concept. LIFO stands for last in first out. In the stack, the insertion and deletion are possible at one end the end is called the top of the stack. In this article, we will see how to reverse a stack using Python. Algorithm: Define some basic function of the stack like push(), pop(), sho
3 min read
Reverse first K elements of the given Stack
Given a stack S and an integer K, the task is to reverse the first K elements of the given stack Examples: Input: S = [ 1, 2, 3, 4, 5, 8, 3, 0, 9 ], K = 4Output: [ 4, 3, 2, 1, 5, 8, 3, 0, 9 ]Explanation: First 4 elements of the given stack are reversed Input: S = [ 1, 2, 3, 4, 5, 8, 3, 0, 9 ], K = 7Output: [ 3, 8, 5, 4, 3, 2, 1, 0, 9 ] Approach: Th
6 min read
Stack Permutations (Check if an array is stack permutation of other)
A stack permutation is a permutation of objects in the given input queue which is done by transferring elements from the input queue to the output queue with the help of a stack and the built-in push and pop functions. The rules are: Only dequeue from the input queue.Use inbuilt push, and pop functions in the single stack.Stack and input queue must
15+ min read
Reversing a Stack with the help of another empty Stack
Given a Stack consisting of N elements, the task is to reverse the Stack using an extra stack. Examples: Input: stack = {1, 2, 3, 4, 5} Output: 1 2 3 4 5 Explanation: Input Stack: 5 4 3 2 1 Reversed Stack: 1 2 3 4 5 Input: stack = {1, 3, 5, 4, 2} Output: 1 3 5 4 2 Approach 1: Follow the steps below to solve the problem: Initialize an empty stack.Po
8 min read
Create a new string by alternately combining the characters of two halves of the string in reverse
Given a string s, create a new string such that it contains the characters of the two halves of the string s combined alternately in reverse order. Examples: Input : s = carbohydratesOutput : hsoebtraarcdy Input : s = sunshineOutput : sennuish Explanation: Example 1: Two halves of the string carbohydrate are carboh and ydrates. As they needed to be
7 min read
Check if a given string is a Reverse Bitonic String or not
Given a string str, the task is to check if that string is a Reverse Bitonic string or not. If the string str is reverse Bitonic string, then print "YES". Otherwise, print "NO". A Reverse Bitonic String is a string in which the characters are arranged in decreasing order followed by increasing order of their ASCII values. Examples: Input: str = "zy
6 min read
Maximize cost of repeated removal of string P or its reverse from the string S
Given two positive integers X and Y and two numeric strings S and P of length N and 2 respectively, the task is to find the maximum total cost obtained by repeatedly removing string P or the reverse of the string P from the string S at the cost of X and Y respectively. Examples: Input: S = "12333444", X = 5, Y = 4, P = "34"Output: 15Explanation:Bel
11 min read
Print reverse of a string using recursion
Write a recursive function to print the reverse of a given string. Code: C/C++ Code // C++ program to reverse a string using recursion #include <bits/stdc++.h> using namespace std; /* Function to print reverse of the passed string */ void reverse(string str) { if(str.size() == 0) { return; } reverse(str.substr(1)); cout << str[0]; } /*
9 min read
Reverse string without using any temporary variable
We are given a string. We are also given indexes of first and last characters in string. The task is to reverse the string without using any extra variable. Examples: Input : str = "abc" Output : str = "cba" Input : str = "GeeksforGeeks" Output : str = "skeeGrofskeeG" If we take a look at program to reverse a string or array, all we need to do is s
4 min read
Sort string of characters using Stack
Given a string of characters. The task is to write a program to print the characters of this string in sorted order using stack. Examples: Input: str = "geeksforgeeks" Output: eeeefggkkorss Input: str = "hello395world216" Output: 123569dehllloorw Approach: Initialize two stacks, one stack, and other tempstack.Insert the first character of the strin
7 min read
Remove all duplicate adjacent characters from a string using Stack
Given a string, str, the task is to remove all the duplicate adjacent characters from the given string. Examples: Input: str= “azxxzy”Output: ay Removal of "xx" modifies the string to “azzy”. Now, the removal of "zz" modifies the string to “ay”. Since the string “ay” doesn't contain duplicates, the output is ay. Input: "aaccdd"Output: Empty String
6 min read
Lexicographically smallest string formed by removing duplicates using stack
Given a string S consisting of lowercase alphabets, the task is to find the lexicographically smallest string that can be obtained by removing duplicates from the given string S. Examples: Input: S = “yzxyz”Output: xyzExplanation: Removing the duplicate characters at indices 0 and 1 in the given string, the remaining string “xyz” consists only of u
8 min read
Reverse Words in a Given String in Python
We are given a string and we need to reverse words of a given string Examples: Input : str =" geeks quiz practice code" Output : str = code practice quiz geeks Input : str = "my name is laxmi" output : str= laxmi is name my Reverse the words in the given string program C/C++ Code # Python code # To reverse words in a given string # input string str
6 min read
Reverse String according to the number of words
Given a string containing a number of words. If the count of words in string is even then reverse its even position's words else reverse its odd position, push reversed words at the starting of a new string and append the remaining words as it is in order. Examples: Input: Ashish Yadav Abhishek Rajput Sunil Pundir Output: ridnuP tupjaR vadaY Ashish
6 min read
Reverse the given string in the range [L, R]
Given a string str, and two integers L and R, the task is to reverse the string in the range [L, R] i.e. str[L...R].Examples: Input: str = "geeksforgeeks", L = 5, R = 7 Output: geeksrofgeeks Reverse the characters in the range str[5...7] = "geeksforgeeks" and the new string will be "geeksrofgeeks" Input: str = "ijklmn", L = 1, R = 2 Output: ikjlmn
4 min read
First substring whose reverse is a word in the string
Given a space-separated string str, the task is to find the first substring whose reverse is a word in the string. All the characters of the string are lowercase English alphabet. The string ends with #. If no such substring is present, return -1 Examples: Input: str = "mango is sweet when nam en tastes it#" Output: man Explanation: Substring "man"
6 min read
Reverse all the word in a String represented as a Linked List
Given a Linked List which represents a sentence S such that each node represents a letter, the task is to reverse the sentence without reversing individual words. For example, for a given sentence "I love Geeks for Geeks", the Linked List representation is given as: I-> ->l->o->v->e-> ->G->e->e->k->s-> ->f-
15 min read
Reverse the substrings of the given String according to the given Array of indices
Given a string S and an array of indices A[], the task is to reverse the substrings of the given string according to the given Array of indices.Note: A[i] ? length(S), for all i.Examples: Input: S = "abcdef", A[] = {2, 5} Output: baedcf Explanation: Input: S = "abcdefghij", A[] = {2, 5} Output: baedcjihgf Approach: The idea is to use the concept of
10 min read
Article Tags :
Practice Tags :