Recovering lost commits with reflog in Git - Time & Space Complexity
When using git reflog to recover lost commits, it's important to understand how the time to find a commit grows as the reflog grows.
We want to know how the number of steps changes when the reflog has more entries.
Analyze the time complexity of the following git commands.
git reflog
# shows list of recent HEAD changes
git checkout <commit-hash>
# moves to the lost commit
# or
git reset --hard <commit-hash>
# restores the branch to that commit
This code shows how to list recent commits and recover a lost commit by checking it out or resetting.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning the reflog entries to find the target commit.
- How many times: The reflog is scanned entry by entry until the commit is found.
As the number of reflog entries grows, the time to find a commit grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 entries scanned |
| 100 | About 100 entries scanned |
| 1000 | About 1000 entries scanned |
Pattern observation: The time grows linearly as the reflog size increases.
Time Complexity: O(n)
This means the time to find a lost commit grows in direct proportion to the number of reflog entries.
[X] Wrong: "git reflog instantly finds any commit no matter how many entries there are."
[OK] Correct: The reflog is a list scanned from newest to oldest, so more entries mean more scanning time.
Understanding how git commands scale with data size shows you think about efficiency and system behavior, a valuable skill in real projects.
"What if git stored reflog entries in a database with indexes? How would the time complexity change?"