ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Bash String Reversal

Bash

Goal -- WPM

Ready
Exercise Algorithm Area
1#!/bin/bash
2
3# Function to reverse a string
4reverse_string() {
5local input_string="$1"
6local reversed_string=""
7local len=${#input_string}
8
9# Handle empty string edge case
10if [ "$len" -eq 0 ]; then
11echo ""
12return
13fi
14
15# Iterate from the last character to the first
16for (( i=$len-1; i>=0; i-- )); do
17reversed_string+="${input_string:$i:1}"
18done
19
20echo "$reversed_string"
21}
22
23# Example usage:
24# original="hello"
25# reversed=$(reverse_string "$original")
26# echo "Original: $original, Reversed: $reversed"
Algorithm description viewbox

Bash String Reversal

Algorithm description:

This Bash script defines a function `reverse_string` that takes a single string argument and returns its reversed version. It iterates through the input string from the last character to the first, appending each character to a new string. This is a fundamental string manipulation task useful in various text processing scenarios.

Algorithm explanation:

The `reverse_string` function reverses a given string. It initializes an empty `reversed_string` and gets the length of the `input_string`. An edge case for an empty string is handled by returning an empty string immediately. The core logic uses a `for` loop that iterates backward from the last index (`len-1`) down to 0. In each iteration, it extracts a single character from the `input_string` at the current index `i` using substring expansion `${input_string:$i:1}` and appends it to `reversed_string`. The time complexity is O(n), where n is the length of the string, because each character is processed once. The space complexity is also O(n) to store the reversed string. The loop boundaries are crucial for correctness, ensuring all characters are included and in the correct order.

Pseudocode:

function reverse_string(input_string):
  if input_string is empty:
    return empty string
  
  reversed_string = ""
  length = length of input_string
  
  for i from length - 1 down to 0:
    append character at index i of input_string to reversed_string
  
  return reversed_string