DSA interview question
A network engineer is checking packet checksums: each packet carries an integer, and a known corruption pattern shows up as a contiguous run of packets whose XOR equals a specific value K. The task is to count how many such runs exist in a capture. Checking every subarray is O(n²). XOR behaves like addition for prefix sums, with one bonus: it is its own inverse. The XOR of a[j+1..i] is prefix[i] ^ prefix[j], so a subarray ending at i has XOR K exactly when some earlier prefix equals prefix[i] ^ K. A hash map of prefix-XOR counts makes this O(n).
Example: [4, 2, 2, 6, 4], K = 6 → 4.
long long countSubarraysWithXor(const vector<int>& a, int k);
Input (a, k) | Output | Explanation |
|---|---|---|
([4, 2, 2, 6, 4], 6) | 4 | [4, 2], [4, 2, 2, 6, 4], [2, 2, 6], [6] |
([5, 6, 7, 8, 9], 5) | 2 | [5] and the whole array |
([1, 1, 1], 1) | 4 | Each single [1], plus [1, 1, 1] |
([0, 0], 0) | 3 | [0], [0], [0, 0] |
([3], 3) | 1 | |
([1, 2, 3], 7) | 0 |
(Confirm: values are non-negative integers; count every (start, end) pair whose XOR is k.)
prefix[i] ^ prefix[j] give the XOR of a[j+1..i]?"On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in