PPractick

DSA interview question

Check Whether the K-th Bit Is Set

Easy · Algorithms · Topics: bit manipulation

The problem

A permissions system stores each user's rights as bits of one integer: bit 0 = read, bit 1 = write, bit 2 = delete, and so on. Before an action runs, the server must answer "is bit k of this user's permission mask set?" millions of times a second. The answer is a single shift and mask: move bit k down to position 0 and check it, or build a mask with only bit k set and AND it with the number.

Example: n = 4 (binary 100), k = 2 → true; k = 0 → false.

Function signature

bool isKthBitSet(int n, int k);  // k = 0 is the least significant bit, 0 <= k <= 31

Test cases

Input (n, k)OutputExplanation
(4, 0)false4 = 100
(4, 2)true
(500, 3)false500 = 111110100
(500, 4)true
(-1, 31)trueThe sign bit of −1 is set

(Confirm: bits are numbered from 0 at the least significant end; n may be negative, in which case its two's complement bits are checked.)

How interviewers phrase it

Clarifying questions to ask

  1. Is k 0-indexed or 1-indexed, and from which end?
  2. Can n be negative?
  3. What's the range of k? (0 to 31 for a 32-bit int.)

Follow-ups to expect

  1. "Right shift or left shift?"
  2. "What goes wrong with 1 << 31?"
  3. "How do you set, clear and toggle bit k?"
  4. "Why is this O(1)?"
  5. "How do you check several bits at once?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in