Clarify input, write the smallest correct solution, name its failure cases, and state time/space complexity. For operational scripts, add a dry run, bounded execution, and an honest failure result. Examples use Python 3; filesystem mutations assume a private directory with no concurrent writers.

All six interview guides.

How do you rename directory files to lowercase and handle edge cases?

Build the complete plan first. Reject colliding names and existing targets, including broken symlinks. This version handles immediate regular files, skips symlinks/directories, and applies only when explicitly requested. It assumes a case-sensitive POSIX filesystem supporting hard links.

import os
from pathlib import Path

def lowercase_files(directory, apply=False):
    plan = []
    targets = set()
    for src in sorted(Path(directory).iterdir()):
        if src.is_symlink() or not src.is_file():
            continue
        dst = src.with_name(src.name.lower())
        if src == dst:
            continue
        if dst in targets or os.path.lexists(dst):
            raise FileExistsError(f"collision: {dst}")
        targets.add(dst)
        plan.append((src, dst))

    if apply:
        for src, dst in plan:
            os.link(src, dst, follow_symlinks=False)
            os.unlink(src)
    return plan

lowercase_files("scratch") previews; lowercase_files("scratch", apply=True) applies. The hard-link step fails if the destination appears, instead of overwriting it. This is not an atomic batch: if interrupted after linking, both names may exist. Stop on errors and inspect the plan; protecting against concurrent source replacement needs stronger directory locking/descriptor-based operations. See Python filesystem operations.

Tests to say aloud: empty directory; already lowercase; A with a; A with another name folding to a; spaces/newlines; broken symlink at a destination; unsupported hard links. Sorting costs O(n log n); plan space is O(n).

How do you return usernames for all duplicate UIDs in /etc/passwd?

Parse the UID field as an integer, group names, and print every group with more than one name. Do not overwrite the first username in a plain UID-to-name mapping.

from collections import defaultdict

def duplicate_uids(lines):
    names = defaultdict(list)
    for number, line in enumerate(lines, 1):
        fields = line.rstrip("\n").split(":")
        if len(fields) != 7:
            raise ValueError(f"bad passwd row {number}")
        names[int(fields[2])].append(fields[0])
    return {uid: users for uid, users in names.items()
            if len(users) > 1}

with open("/etc/passwd", encoding="utf-8") as source:
    for uid, users in sorted(duplicate_uids(source).items()):
        print(uid, *users)

O(n) parsing time and storage. Test a repeated UID, distinct UIDs, UID 0, malformed rows, and an empty input. This reads local /etc/passwd; enterprise identities can require getent passwd or a directory-service query.

How do you upgrade hosts, reboot when required, and verify they return?

Use a durable per-host state machine with bounded batches. Make package/reboot detection distribution-specific; a disconnected SSH session does not prove reboot or success.

for a bounded batch, respecting replica/failure-domain capacity:
    confirm preflight health and record boot ID + package versions
    drain traffic and verify remaining serving capacity
    apply the distribution's noninteractive upgrade with a deadline
    inspect the result and that distribution's reboot requirement
    if reboot required:
        request reboot
        wait with a deadline for authenticated access and a changed boot ID
    verify target packages/kernel, required services, and application requests
    rejoin traffic gradually and watch error/latency/backlog limits
    persist success; stop rollout on failed or unknown outcomes

Every remote command needs a timeout, a captured exit status, and verified host identity. Record checkpoints so reruns reconcile actual state. Blindly retrying an upgrade after an SSH timeout can start competing package operations. Keep failed hosts drained; if remaining capacity cannot tolerate that, stop the next batch. Package/database rollback needs its own compatibility plan.

How do you write a babysitter that restarts a stopped webserver?

On a systemd host, supervise the foreground process with a service unit. Restarting on failure belongs in the service manager; a shell polling loop can miss exits, race with another supervisor, and loop endlessly.

[Unit]
Description=Interview example webserver
StartLimitIntervalSec=60
StartLimitBurst=5

[Service]
Type=simple
User=www-data
ExecStart=/opt/example/bin/webserver --foreground
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Replace the user, path, and flags for the real application. on-failure covers abnormal exits; always also restarts ordinary clean exits, while an explicit manager stop still stops it. Neither detects a live-but-hung process without an additional watchdog/health mechanism. Rate limits prevent unlimited restart storms. See systemd service semantics.

How do you find the ten most-used words in a file?

Define "word" and ties before coding. This version counts case-insensitive ASCII letter runs, so can't becomes can and t. Ties sort alphabetically for reproducible output.

import re
from collections import Counter

def top_words(lines, k=10):
    counts = Counter()
    for line in lines:
        counts.update(re.findall(r"[a-z]+", line.lower()))
    return sorted(counts.items(), key=lambda item: (-item[1], item[0]))[:k]

For b input characters and v distinct words: O(b + v log v) time and O(v + longest line) memory, allowing for sorting storage. Reading line by line avoids loading the entire file, but distinct-word counts still grow. A vocabulary exceeding RAM needs external aggregation; a heap can reduce final top-k selection cost. See Counter.

With 1,000 video files, how do you print duplicates and safely remove them?

Group by size, hash only equal-size candidates, then byte-compare before declaring duplicates. Filenames and timestamps do not prove equality. The function below returns a read-only plan of (keep, duplicate) pairs; it skips symlinks and treats existing hard links as the same stored file.

import hashlib
from collections import defaultdict
from pathlib import Path

def fingerprint(path):
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.digest()

def same_bytes(left, right):
    with left.open("rb") as a, right.open("rb") as b:
        while True:
            x, y = a.read(1024 * 1024), b.read(1024 * 1024)
            if x != y:
                return False
            if not x:
                return True

def duplicate_plan(directory):
    sizes, seen, plan = defaultdict(list), set(), []
    for path in sorted(Path(directory).iterdir()):
        if path.is_symlink() or not path.is_file():
            continue
        info = path.stat()
        identity = (info.st_dev, info.st_ino)
        if identity not in seen:
            seen.add(identity)
            sizes[info.st_size].append(path)
    for paths in sizes.values():
        if len(paths) < 2:
            continue
        hashes = defaultdict(list)
        for path in paths:
            candidates = hashes[fingerprint(path)]
            for keep in candidates:
                if same_bytes(keep, path):
                    plan.append((keep, path))
                    break
            else:
                candidates.append(path)
    return plan

Print paths with repr() so newlines are unambiguous. For removal, freeze writers, review the plan and retention rules, revalidate identity/content, and move approved duplicates into a recoverable quarantine using a no-overwrite operation. Delete after verifying retained files and the recovery window. This scanner alone is not safe against hostile concurrent filesystem changes.

Hashing reads O(B) candidate bytes; byte comparisons add reads and contrived digest collisions can increase comparison work. Planning uses O(n) entries plus bounded read buffers. SHA-256 equality is only a candidate filter here; exact byte comparison establishes equal contents. See hashlib.

How do you generate passwords and SSH keys for automation?

Use a cryptographic generator, distinct credentials per host/identity, scoped access, and audited storage. Automation authentication and secret retrieval are separate problems. The three original credential prompts are answered in the security guide.

The linked stream question: add numbers and return kth largest

The candidate account linked in the preparation list describes an in-memory stream with duplicates and a different k allowed on each query. An ascending sorted list is a simple correct implementation:

from bisect import insort

class RankedStream:
    def __init__(self):
        self.values = []

    def addNum(self, value):
        insort(self.values, value)

    def findLargest(self, k):
        if k < 1 or k > len(self.values):
            return None
        return self.values[-k]

Duplicates occupy separate ranks; k == len(values) returns the minimum. Empty input and nonpositive/out-of-range ranks return None, since negative numbers can be valid data. List insertion costs O(n), query O(1), storage O(n); binary search does not eliminate shifting. See bisect.

For fixed k, a size-k min-heap supports O(log k) insertion and O(1) kth-largest lookup once enough values exist. An ordinary heap cannot answer arbitrary ranks in O(1); an order-statistics tree can trade more complexity for logarithmic updates/queries.

The account's advancing-rank follow-up needs an explicit contract when insertions occur between reads. Under a "next rank in the current collection" contract, advance a rank counter after each query; a newly inserted larger value can shift previous results into later ranks. If the requirement is instead "return each inserted element at most once, always largest remaining," use a max-heap and destructive pop. These are different problems; confirm which one is intended.

Ten-minute drill

Implement duplicate UID grouping and word counting from memory. For filenames, predict collision behavior before applying any plan. For host upgrades, describe what happens if SSH disappears after the package command starts. Next: security and credentials.