In a lesson from a coding course that covers Data Structures and Algorithms, there's a program that seeks to find all palindromes in a list of usernames. The program is analyzed for space complexity. The function `findAllPalindromes` goes through each username, checks if it's a palindrome using `isPalindrome`, and adds it to a result array if it is. The question arises: If the reversed usernames are only used temporarily and don't remain in memory, shouldn't the space complexity simply be O(n) instead of O(n * k), where k represents the length of the usernames?
3 Answers
You're right to think about space usage! The reason it's O(n * k) is that in the worst-case scenario, when every username is a palindrome, the program needs to store all of them. So, if you have n usernames, each averaging k characters, you end up needing space for all of them in the result, hence O(n * k).
It's worth noting that if you disregard the result array for a moment, you could simplify it to O(n). The space that's consistently used for checks, like the temporary storage within the `isPalindrome` function, is minimal compared to the final results you're storing.
Think of it this way: if you're assessing the complexity at a high level, it might seem like O(n), but since every string has its individual character count, that's where the k comes in. So, k is significant in the overall complexity. You can't ignore it if you're considering the memory footprint!

Good point! If we focus strictly on the operations performed without accounting for what gets stored in the result array, you might justify a simpler O(n) space complexity. But remember that the overall function's goal is to give back all palindromes, hence the larger picture is where O(n * k) comes from.