Skip to main content
Cloud, DevOps & Systems

Git & GitHub Interview Questions

All Levels (Junior to Staff)16 Questions

Git internals interview guide covering content-addressable storage (blobs, trees, commits), rebase vs merge algorithms, and reflog recovery.

20 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice Git & GitHub Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

What are the three areas of a Git repository (Working Tree, Staging Index, and Local Repository), and how do files move between them?

Senior Engineering Answer

The Working Tree holds the checked-out files you edit on disk. The Staging Index (.git/index) is a binary snapshot listing the exact file blobs and modes prepared for the next commit. The Local Repository (.git/objects and refs) permanently stores committed snapshots in the DAG. Running git add hashes file contents into a blob object and updates the index; git commit writes tree and commit objects referencing that index snapshot.

Production Code Example
git status -s
git add src/auth.ts       # Working Tree -> Staging Index
git restore --staged src/auth.ts  # Unstage without losing working edits
Common Interview Trap / Anti-Pattern:

Thinking git add only tracks filenames; Git snapshots exact file contents at the moment you run git add, so subsequent edits require running git add again before committing.

Question #2FundamentalJunior

What is the difference between git fetch and git pull?

Senior Engineering Answer

git fetch downloads new commits, tags, and branch pointers from the remote repository into remote-tracking branches (such as origin/main) without touching your local working branch or uncommitted changes. git pull runs git fetch followed immediately by either git merge (default) or git rebase (with --rebase) into your currently checked-out branch.

Production Code Example
git fetch origin
git log HEAD..origin/main --oneline   # Inspect incoming commits before integrating
git rebase origin/main
Common Interview Trap / Anti-Pattern:

Running git pull blindly on a branch with local commits creates noisy automatic merge commits ('Merge branch main of ...') unless pull.rebase or --ff-only is configured.

Question #3FundamentalJunior

What is a detached HEAD state in Git, and how do you rescue commits created while detached?

Senior Engineering Answer

Normally, HEAD is a symbolic reference pointing to a branch ref (like ref: refs/heads/main). Detached HEAD means HEAD points directly to a raw commit SHA-1/SHA-256 hash—often triggered by checking out a tag, commit hash, or origin/main directly. Any new commits made while detached advance HEAD alone and become unreachable once you switch away unless you attach a branch with git switch -c <branch>.

Production Code Example
# Save commits created in detached HEAD before switching branches
git switch -c rescue-feature
# Or if already switched away, find the hash via reflog:
git reflog -n 10
Common Interview Trap / Anti-Pattern:

Assuming commits made in detached HEAD are deleted immediately upon checking out main; they remain intact in .git/objects until garbage collection (default 30+ days) and can be recovered via git reflog.

Question #4FundamentalJunior

What is the difference between git reset (--soft, --mixed, --hard) and git revert?

Senior Engineering Answer

git reset moves the current branch pointer backward (rewriting local history): --soft leaves changes staged in the index, --mixed (the default) unstages them into the working directory, and --hard resets the index and working tree to match the target commit, discarding uncommitted edits. git revert leaves existing commits untouched and creates a brand-new commit applying the inverse diff, making it safe for shared remote branches.

Production Code Example
# Undo last 2 local unpushed commits while keeping edits staged to squash
git reset --soft HEAD~2
# Safely undo a commit already pushed to main
git revert <commit-sha>
Common Interview Trap / Anti-Pattern:

Running git reset --hard and force-pushing to a shared main branch breaks collaborators' histories and can permanently discard untracked vs tracked edits.

Question #5IntermediateMid-Level

How do Git's four internal object types (blob, tree, commit, annotated tag) form a content-addressable DAG?

Senior Engineering Answer

Git stores everything under .git/objects keyed by the cryptographic hash of its header and zlib-compressed payload. A blob stores raw file bytes without a filename. A tree maps filenames, Unix permissions, and modes to blob or subtree hashes. A commit object points to one root tree hash, zero or more parent commit hashes, author/committer metadata, and the commit message—forming a Merkle Directed Acyclic Graph (DAG). An annotated tag wraps a commit hash with tagger metadata and optional GPG/SSH signature.

Production Code Example
git cat-file -t HEAD      # Prints: commit
git cat-file -p HEAD      # Prints tree hash, parent hash(es), author, message
git ls-tree HEAD          # Lists mode, type, hash, and path in root tree
Common Interview Trap / Anti-Pattern:

Believing Git stores commits as file-by-file diffs; every commit points to a complete root tree snapshot, with identical unchanged files deduplicated by sharing the same blob hash.

Question #6IntermediateMid-Level

How do git merge (fast-forward vs 3-way) and git rebase differ, and when should you choose each?

Senior Engineering Answer

If the target branch has no new commits since branching, git merge performs a fast-forward by simply advancing the pointer. If branches diverged, a 3-way merge compares both branch tips against their merge-base ancestor and creates a two-parent merge commit, preserving exact branch topology. git rebase replays your branch's commits one by one atop the latest upstream tip with new commit hashes, yielding a linear history that simplifies git bisect and code review.

Production Code Example
# Rebase local feature branch cleanly before opening PR
git fetch origin
git rebase origin/main
# Safe force push after rebasing a personal PR branch
git push --force-with-lease
Common Interview Trap / Anti-Pattern:

Rebasing commits that teammates have already branched off or running git push --force instead of --force-with-lease, which can silently overwrite a teammate's newly pushed commits.

Question #7IntermediateMid-Level

How do you use interactive rebase (git rebase -i) with squash, fixup, and autosquash to clean commit history?

Senior Engineering Answer

git rebase -i opens a todo list letting you reorder, edit, drop, reword, or combine commits before merging a PR. 'squash' folds a commit into the previous one and opens an editor to combine commit messages; 'fixup' folds changes in while discarding the fixup message. Creating commits with git commit --fixup <sha> and running git rebase -i --autosquash main automatically reorders and marks fixup commits cleanly.

Production Code Example
git commit --fixup a1b2c3d
git rebase -i --autosquash origin/main
Common Interview Trap / Anti-Pattern:

Resolving the same merge conflict repeatedly during a long interactive rebase; enabling git config --global rerere.enabled true teaches Git to record and replay conflict resolutions automatically.

Question #8IntermediateMid-Level

How does git bisect find the exact commit that introduced a bug, and how can you automate it?

Senior Engineering Answer

git bisect performs a binary search across the commit DAG between a known broken commit (bad) and an earlier working commit (good), checking out midpoint commits so you isolate the regression in O(log2 N) steps instead of testing hundreds of commits linearly. Passing a test command to git bisect run automates the entire search without manual input—provided the script returns exit code 0 for good, 1-127 (except 125) for bad, and 125 to skip unbuildable commits.

Production Code Example
git bisect start HEAD v2.4.0
git bisect run npm test -- --grep "checkout tax"
git bisect reset
Common Interview Trap / Anti-Pattern:

Forgetting to run git bisect reset afterward leaves your repository in a detached HEAD bisect state, and forgetting exit code 125 on broken-build commits can misattribute the regression.

Question #9AdvancedSenior

How does git reflog work internally to recover deleted branches or botched rebases, and when do unreachable objects actually disappear?

Senior Engineering Answer

Every time HEAD or a local branch tip moves (commit, checkout, reset, rebase, merge), Git appends an entry to .git/logs/HEAD and .git/logs/refs/heads/<branch>. Those reflog entries protect old commits from garbage collection until they expire—defaulting to 90 days for reachable history moves (gc.reflogExpire) and 30 days for unreachable commits (gc.reflogExpireUnreachable). Until git gc prunes expired unreachable objects (default prune age 2 weeks), any lost state can be restored.

Production Code Example
git reflog show feature/auth
# Recover pre-rebase branch state cleanly
git reset --hard feature/auth@{1}
# Or scan dangling commits if reflog was cleared:
git fsck --lost-found
Common Interview Trap / Anti-Pattern:

Deleting .git/refs or cloning afresh loses reflogs completely because reflogs are strictly local and never pushed to or fetched from remote repositories.

Question #10AdvancedSenior

What happens during a 3-way merge conflict in Git's index (stages 1, 2, 3), and how do conflict style diff3/zdiff3 help resolve complex merges?

Senior Engineering Answer

When a 3-way merge hits overlapping edits, Git pauses and stores up to three versions of the conflicted file in the staging index: stage 1 is the common merge-base ancestor, stage 2 is 'ours' (current HEAD), and stage 3 is 'theirs' (incoming branch). Enabling merge.conflictStyle = zdiff3 adds the common ancestor block (|||||||) between <<<<<<< and >>>>>>> markers and trims identical surrounding lines, making it immediately obvious what each branch actually changed relative to the base.

Production Code Example
git config --global merge.conflictStyle zdiff3
# Inspect stage 1 (base), 2 (ours), 3 (theirs) during conflict:
git show :1:src/config.ts
Common Interview Trap / Anti-Pattern:

Resolving a conflict by guessing between HEAD and incoming changes without seeing the common ancestor often reintroduces deleted code or drops a subtle refactor from one side.

Question #11AdvancedSenior

How do Git packfiles (.pack / .idx) and delta compression keep repository storage small?

Senior Engineering Answer

Initially Git writes each blob, tree, and commit as a separate loose object file under .git/objects/xx/. Periodically (via git gc, git repack, or network transfer), Git packs objects into a single binary .pack archive accompanied by a .idx binary search index. Inside a packfile, Git groups similar objects by filename/size heuristics and stores recent versions as full snapshots while encoding older or similar variants as compressed binary deltas (zlib-compressed instructions referencing base objects).

Production Code Example
git count-objects -vH
git gc --aggressive --prune=now
Common Interview Trap / Anti-Pattern:

Checking large binary assets (videos, JARs, ML weights) into Git repeatedly defeats delta compression across compressed formats, permanently bloating clone sizes for every engineer unless Git LFS is used.

Question #12AdvancedSenior

How do Git Worktrees let you work on multiple branches simultaneously without stashing or re-cloning?

Senior Engineering Answer

git worktree creates additional linked working directories backed by a single shared .git object database and remote refs. Each worktree maintains its own checked-out branch, HEAD, and staging index, letting you review a PR, run a slow test suite, or ship an urgent hotfix in a sibling directory without disturbing long-running builds or uncommitted work in your primary checkout.

Production Code Example
git worktree add ../repo-hotfix -b hotfix/tls origin/main
# When finished:
git worktree remove ../repo-hotfix
Common Interview Trap / Anti-Pattern:

Trying to check out the same branch concurrently in two different worktrees is blocked by Git to prevent conflicting index/ref updates; create a detached checkout or separate branch instead.

Question #13StaffPrincipal / Staff

How do you scale Git monorepos with thousands of developers using partial clones, sparse-checkout, commit-graph, and scalar?

Senior Engineering Answer

Full clones of multi-million-file monorepos choke on object transfer and git status stat() scans. Partial clones (git clone --filter=blob:none) download commits and trees immediately while fetching file blobs lazily on demand. Sparse-checkout in cone mode materializes only the directories a team works on, dramatically cutting working-tree I/O. Enabling core.commitGraph precomputes topological generation numbers for O(1) ancestry checks, and fsmonitor replaces full-tree filesystem scans with OS file-watcher daemons—bundled together via git scalar.

Production Code Example
git clone --filter=blob:none --sparse https://github.com/org/monorepo.git
cd monorepo
git sparse-checkout set --cone services/billing libs/shared
git maintenance start
Common Interview Trap / Anti-Pattern:

Using non-cone pattern matching in .git/info/sparse-checkout instead of --cone forces O(files * patterns) regex evaluations on every checkout, negating sparse-checkout speedups.

Question #14StaffPrincipal / Staff

How do you permanently purge accidentally committed secrets or large binaries from an entire Git history using git-filter-repo?

Senior Engineering Answer

Simply deleting a secret in a new commit leaves it readable in earlier commits. Modern Git replaces slow, error-prone git filter-branch with git-filter-repo, which streams fast-export/fast-import rewrites across all commits, trees, and tags while stripping target files or replacing secret strings across history. Afterward, all collaborators must rebase or re-clone, force-push rewritten refs, contact hosting support to purge cached PR/ref objects, and rotate the exposed credentials immediately.

Production Code Example
# Strip an accidentally committed .env file from every commit in history
git filter-repo --invert-paths --path config/.env.prod
# Replace a leaked API key across all blobs via expressions file
git filter-repo --replace-text secrets.txt
Common Interview Trap / Anti-Pattern:

Assuming force-pushing rewritten history deletes the secret from GitHub immediately; old commit hashes can remain accessible via pull request refs (refs/pull/*/head), fork caches, or CI artifacts unless credentials are revoked.

Question #15StaffPrincipal / Staff

How do GitHub branch protection rulesets, merge queues, CODEOWNERS, and signed commits enforce secure SDLC governance at scale?

Senior Engineering Answer

At high merge velocity, two PRs that each pass CI against main independently can break main when merged sequentially (semantic conflicts). GitHub Merge Queues group approved PRs, merge them speculatively in sequence onto main, and run full CI on the combined state before advancing main. Pairing Merge Queues with Rulesets (requiring CODEOWNERS approval, linear history or squash-only merges, passing status checks, and SSH/GPG/Sigstore commit verification) prevents unreviewed or broken code from landing.

Production Code Example
# .github/CODEOWNERS
/services/payments/ @org/payments-security @org/staff-backend
/.github/workflows/ @org/platform-infra
Common Interview Trap / Anti-Pattern:

Enabling 'Dismiss stale pull request approvals' without a Merge Queue on busy repositories forces engineers into an endless race condition rebasing and re-requesting reviews.

Question #16StaffPrincipal / Staff

How do GitHub Actions OIDC federation, pinned action SHAs, and workflow isolation prevent CI/CD supply-chain compromise?

Senior Engineering Answer

Storing long-lived AWS/GCP keys in GitHub Secrets exposes static credentials if a workflow is compromised. GitHub OIDC issues short-lived signed JWTs scoped to repo, branch, and environment claims that cloud STS validates directly for temporary role credentials. To prevent third-party action hijacking (like tag-repointing attacks), pin every uses: step to an immutable 40-char commit SHA, enforce minimal permissions: {} at workflow level, and avoid pull_request_target executing untrusted fork code with write tokens.

Production Code Example
permissions:
  id-token: write
  contents: read
steps:
  - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
  - uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c199c265338f12b4b6a1d9
    with:
      role-to-assume: arn:aws:iam::123456789012:role/github-deploy
      aws-region: us-east-1
Common Interview Trap / Anti-Pattern:

Using pull_request_target and checking out ${{ github.event.pull_request.head.sha }} allows an external fork PR to execute arbitrary code with access to production secrets and repository write permissions.

Git & GitHub Track Coverage & Difficulty Profile

16 of 16 prompts include code examples

This Git & GitHub preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Cloud, DevOps & Systems.

JuniorFundamental

What are the three areas of a Git repository (Working Tree, Staging Index, and Local Repository), and how do files move between them?

JuniorFundamental

What is the difference between git fetch and git pull?

JuniorFundamental

What is a detached HEAD state in Git, and how do you rescue commits created while detached?

JuniorFundamental

What is the difference between git reset (--soft, --mixed, --hard) and git revert?

Mid-LevelIntermediate

How do Git's four internal object types (blob, tree, commit, annotated tag) form a content-addressable DAG?

Mid-LevelIntermediate

How do git merge (fast-forward vs 3-way) and git rebase differ, and when should you choose each?

Frequently Asked Technical Interview Questions (Git & GitHub)

Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.

What is the difference between git switch/restore and legacy git checkout?
git checkout overloaded two unrelated jobs: switching branches and overwriting working files. Modern Git splits these cleanly into git switch (for creating and switching branches) and git restore (for discarding working-tree changes or unstaging files from the index), eliminating accidental file overwrites.
When should a team use Squash and Merge versus Rebase and Merge on GitHub Pull Requests?
Squash and Merge condenses messy WIP commits into a single atomic commit per PR on main, keeping release notes and reverts trivial. Rebase and Merge preserves individual well-crafted commits linearly on main when a PR contains logically distinct, individually bisectable changes.
How do Git Submodules differ from Git Subtrees and package registries?
Git Submodules embed a pointer to a specific commit SHA of an external repository, requiring extra clone/update flags (--recursive) and explicit version bumps. Git Subtrees merge external history directly into a subdirectory without extra clone steps. For versioned libraries, publishing artifacts to a package registry (npm, PyPI, Maven) is usually cleaner than both.
Why does Git show modified files after changing only line endings (CRLF vs LF) across Windows and Linux?
Operating systems use different line terminators (LF on Linux/macOS, CRLF on Windows). Configuring a repository .gitattributes file (e.g., * text=auto eol=lf) enforces consistent LF normalization in the Git object store regardless of each developer's OS core.autocrlf setting.
Complete Learning Ecosystem

Pair Interview Prep with Cheat Sheets & Roadmaps

Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.

Want to practice other technologies?

Explore our comprehensive technical interview tracks across all core technology stacks.

Browse All Interview Tracks