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

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

Bash Script: Find Longest Common Prefix

Bash

Goal -- WPM

Ready
Exercise Algorithm Area
1#!/bin/bash
2
3# Function to find the longest common prefix among an array of strings.
4# Arguments: $@ - An array of strings.
5# Returns: The longest common prefix string.
6find_longest_common_prefix() {
7local strings=($@)
8local num_strings=${#strings[@]}
9
10# Edge case: If the array is empty, return an empty string.
11if [ "$num_strings" -eq 0 ]; then
12echo ""
13return
14fi
15
16# Edge case: If there's only one string, it's the prefix.
17if [ "$num_strings" -eq 1 ]; then
18echo "${strings[0]}"
19return
20fi
21
22# Initialize the prefix with the first string.
23local prefix="${strings[0]}"
24
25# Iterate through the rest of the strings.
26for ((i = 1; i < num_strings; i++)); do
27local current_string="${strings[$i]}"
28local current_prefix_len=${#prefix}
29local current_string_len=${#current_string}
30local j=0
31
32# Compare characters of the current prefix and the current string.
33while [ "$j" -lt "$current_prefix_len" ] && [ "$j" -lt "$current_string_len" ] && [ "${prefix:$j:1}" = "${current_string:$j:1}" ]; do
34j=$((j + 1))
35done
36
37# Update the prefix to the common part found.
38prefix="${prefix:0:$j}"
39
40# If the prefix becomes empty, we can stop early.
41if [ -z "$prefix" ]; then
42break
43fi
44done
45
46echo "$prefix"
47}
48
49# Example Usage:
50# declare -a my_strings=("flower" "flow" "flight")
51# echo "Longest common prefix: $(find_longest_common_prefix "${my_strings[@]}")"
52
53# declare -a another_set=("dog" "racecar" "car")
54# echo "Longest common prefix: $(find_longest_common_prefix "${another_set[@]}")"
55
56# declare -a single_string=("apple")
57# echo "Longest common prefix: $(find_longest_common_prefix "${single_string[@]}")"
58
59# declare -a empty_set=()
60# echo "Longest common prefix: $(find_longest_common_prefix "${empty_set[@]}")"
Algorithm description viewbox

Bash Script: Find Longest Common Prefix

Algorithm description:

This Bash script defines a function `find_longest_common_prefix` that takes an array of strings as input and returns the longest common prefix among them. It handles edge cases such as an empty input array or an array containing only one string. This is useful for tasks like organizing files with similar naming conventions or processing data where common prefixes indicate related entries.

Algorithm explanation:

The `find_longest_common_prefix` function works by initializing the potential prefix with the first string in the input array. It then iterates through the remaining strings, comparing each character of the current prefix with the corresponding character in the current string. The prefix is truncated whenever a mismatch is found or when the end of either string is reached. This process continues until all strings have been compared. If at any point the prefix becomes an empty string, the function terminates early, as no further common prefix can exist. The time complexity is O(S), where S is the sum of all characters in all strings, as each character might be compared at most once. The space complexity is O(1) because only a few variables are used to store intermediate results.

Pseudocode:

function find_longest_common_prefix(strings):
  if strings is empty:
    return ""
  if strings has one element:
    return the element

  prefix = first string in strings

  for each string from the second string onwards in strings:
    common_length = 0
    while common_length < length(prefix) AND common_length < length(current_string) AND prefix[common_length] == current_string[common_length]:
      increment common_length
    prefix = substring of prefix from start to common_length
    if prefix is empty:
      break

  return prefix