String to array and array to string in PostgreSQL - Time & Space Complexity
We want to understand how the time needed to convert strings to arrays and back changes as the input size grows.
How does the work increase when the string or array gets longer?
Analyze the time complexity of the following code snippet.
-- Convert a string to an array by splitting on commas
SELECT string_to_array('apple,banana,cherry', ',');
-- Convert an array back to a string with commas
SELECT array_to_string(ARRAY['apple', 'banana', 'cherry'], ',');
This code splits a string into parts using a separator and joins an array of strings back into one string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each character of the input string or each element of the array.
- How many times: Once for each character in the string when splitting, and once for each array element when joining.
As the string or array gets longer, the work grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character checks or 10 array elements processed |
| 100 | About 100 character checks or 100 array elements processed |
| 1000 | About 1000 character checks or 1000 array elements processed |
Pattern observation: The work increases steadily as the input size grows, roughly one step per character or element.
Time Complexity: O(n)
This means the time to convert grows in a straight line with the size of the string or array.
[X] Wrong: "Splitting or joining strings happens instantly no matter the size."
[OK] Correct: Actually, the system must look at each character or element, so bigger inputs take more time.
Understanding how string and array conversions scale helps you reason about data processing speed in real projects.
"What if we changed the separator to a multi-character string? How would the time complexity change?"