Sobes.tech
Junior — Senior

Finding array elements starting with a given prefix

livecode

Task condition

You need to iterate through an array of strings and collect all elements whose beginning matches a given prefix. The function takes two arguments: an array of strings words and a string prefix prefix. The result should be a new collection (array, list, etc.) containing only the strings that start with prefix. If no string satisfies the condition, an empty array is returned.

Example

words = ["apple", "apricot", "banana", "application", "cat"]
prefix = "ap"
# result: ["apple", "apricot", "application"]

Requirements

  • Comparison should be case-sensitive (the string "Apple" does not count as starting with the prefix "ap").
  • The runtime should be linear relative to the number of elements in the array.
  • Memory is only used for storing the result and a few auxiliary variables.

Hint: use the startswith method (or similar) to check the beginning of a string.