TRIM, LTRIM, RTRIM variations in PostgreSQL - Time & Space Complexity
When using TRIM functions in PostgreSQL, it's important to understand how the time to process grows as the text length increases.
We want to know how the trimming operation's cost changes when the input string gets longer.
Analyze the time complexity of these trimming functions.
SELECT TRIM(BOTH ' ' FROM text_column) FROM my_table;
SELECT LTRIM(text_column, ' ') FROM my_table;
SELECT RTRIM(text_column, ' ') FROM my_table;
These queries remove spaces from both ends, left end, or right end of text values in a table.
Look at what repeats when trimming each string.
- Primary operation: Scanning characters from the start and/or end of each string to find where spaces stop.
- How many times: Each character at the edges is checked until a non-space is found.
The trimming scans only the edges, so the work depends on how many spaces are at the start or end, not the whole string length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks if all spaces |
| 100 | Up to 100 checks if all spaces |
| 1000 | Up to 1000 checks if all spaces |
Pattern observation: The number of operations grows linearly with the number of spaces at the edges, not the total string length.
Time Complexity: O(k)
This means the time depends on the number of characters trimmed at the edges, not the full string length.
[X] Wrong: "Trimming always checks every character in the string."
[OK] Correct: Trimming stops as soon as it finds a non-space character at the edges, so it usually does less work than scanning the whole string.
Understanding how trimming functions work helps you reason about string processing efficiency, a useful skill when working with databases and text data.
What if we trim a character that appears frequently inside the string, not just at the edges? How would the time complexity change?