r/AskComputerScience • • Mar 02 '25
Can algorithmic analysis sometimes be misleading ?
Here are some examples in golang. To be honest these are pretty dumb, but just for argument sake.
Program 1: Initializes an array of length 10, each element set to 1
func main() {
arr := [10]int{}
for i := 0; i < 10; i++ {
arr[i] = 1
}
}
Program 2: Initializes an array of length 1 trillion, each element set to 1
func main() {
arr := [1000000000000]int{}
for i := 0; i < 1000000000000; i++ {
arr[i] = 1
}
}
Aren't both both programs O(1) time and space complexity ? Yet program 2 will use way more RAM than program 1.
To be clear, I'm not arguing complexity analysis is pointless. Just trying to understand analysis from both a theoertical and practical perspective.
0
Upvotes
View all comments
Show parent comment
3
u/ghjm MSCS, CS Pro (20+) Mar 03 '25
No, they're O(1) because neither of them have any inputs. Each of them executes in constant time.
It's natural to generalize and think about an array initialization function that takes a parameter n, which would indeed be O(n). But that's not what was given here. This is two different algorithms, each initializing a constant-sized array, and thus each O(1).
This distinction actually does matter, as in the famous Blum-Floyd-Pratt-Rivest-Tarjan median selection algorithm, whose complexity analysis depends on a linear search of exactly 5 elements being O(1).