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

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

Nim Basic String Reversal

Nim

Goal -- WPM

Ready
Exercise Algorithm Area
1proc reverseString(s: string): string =
2var reversed = ""
3for i in countdown(s.len - 1, 0):
4reversed.add(s[i])
5return reversed
6
7proc main() =
8let original = "Nim Programming"
9let reversed = reverseString(original)
10echo "Original: ", original
11echo "Reversed: ", reversed
12
13let empty = ""
14echo "Original: ", empty
15echo "Reversed: ", reverseString(empty)
16
17let singleChar = "A"
18echo "Original: ", singleChar
19echo "Reversed: ", reverseString(singleChar)
20
21main()
Algorithm description viewbox

Nim Basic String Reversal

Algorithm description:

This Nim code defines a simple procedure `reverseString` that takes a string 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 `reverseString` procedure iterates through the input string `s` from its last character (index `s.len - 1`) down to the first character (index 0) using the `countdown` iterator. In each iteration, the character at the current index `i` is appended to the `reversed` string. This builds the reversed string character by character. The time complexity is O(N), where N is the length of the string, because each character is processed exactly once. The space complexity is also O(N) because a new string of the same length is created to store the reversed result. Edge cases like an empty string or a single-character string are handled correctly by the loop bounds.

Pseudocode:

Procedure reverseString(inputString):
  Initialize reversedString as empty
  For i from length(inputString) - 1 down to 0:
    Append character at inputString[i] to reversedString
  Return reversedString