After deploying a recent change, you realize it has caused a significant issue. How would you revert the last commit in your repository while ensuring the change is also removed from the history?

git reset --hard HEAD~1 moves the current branch pointer back one commit and discards that commit's changes from both the working directory and the index, effectively removing it from local history entirely.

Key Points: • The command rewrites the branch's history, unlike git revert, which adds a new commit undoing the change without removing anything. • Because reset discards changes rather than recording an undo, it's best used only on commits that haven't been pushed or shared with others. • If the bad commit was already pushed, a force push (with team coordination) is needed to update the remote, and everyone else must reset or re-clone to match. • git reflog keeps a temporary record of where HEAD has been, so an accidental reset can often be recovered from shortly after the fact. • On shared branches, git revert is generally the safer choice since it preserves history and doesn't require a force push.

Example: A developer commits a change locally, realizes immediately it's broken, and hasn't pushed yet, so they run git reset --hard HEAD~1 to cleanly discard that commit before anyone else ever sees it.

Code Example:

git reset --hard HEAD~1

Interview Tip: A concise interview answer is:

"If the commit hasn't been shared yet, git reset --hard HEAD~1 cleanly removes it and its changes from history. But if it's already pushed, I'd use git revert instead, since it undoes the change with a new commit without rewriting history that others may already have."