Bird
Raised Fist0
Interview Prepbit-manipulationmediumFacebookGoogleAmazon

UTF-8 Validation

Choose your preparation mode4 modes available
🎯
UTF-8 Validation
mediumBIT_MANIPULATIONFacebookGoogleAmazon

When transmitting text data over the internet, ensuring that the byte sequences conform to UTF-8 encoding is crucial to avoid misinterpretation or corruption.

💡 This problem involves checking if a sequence of integers represents a valid UTF-8 encoded string. Beginners often struggle because UTF-8 encoding rules depend on bit patterns in bytes, which requires understanding binary representations and bitmasking.
📋
Problem Statement

Given an array of integers representing bytes, determine if it is a valid UTF-8 encoding. Each integer represents one byte (only the least significant 8 bits are used). UTF-8 encoding rules specify how many bytes a character uses and how continuation bytes must be formatted.

1 ≤ n ≤ 10^5Each integer is in the range 0 to 255 (only 8 bits used)
💡
Example
Input"[197, 130, 1]"
Outputtrue

197 (11000101) starts a 2-byte character, 130 (10000010) is a valid continuation byte, 1 (00000001) is a valid 1-byte character.

Input"[235, 140, 4]"
Outputfalse

235 (11101011) starts a 3-byte character, 140 (10001100) is a valid continuation byte, but 4 (00000100) is not a valid continuation byte.

  • Single byte character only → true
  • Continuation byte without a leading byte → false
  • Leading byte indicating 4-byte character but fewer continuation bytes → false
  • Bytes with leading bits not matching any UTF-8 pattern → false
⚠️
Common Mistakes
Not checking if enough continuation bytes remain after a leading byte

Index out of range error or false positives

✅ Always verify that the number of continuation bytes does not exceed array length

Misinterpreting continuation bytes by not checking the two leading bits are '10'

Invalid UTF-8 sequences accepted as valid

✅ Use bitmask to ensure continuation bytes start with '10'

Incorrectly identifying the number of bytes in a character by wrong bit shifts

Wrong character length leads to validation errors

✅ Use correct bit shifts and masks to identify leading byte patterns

Not verifying that the final continuation byte count is zero at the end

Partial characters at the end accepted as valid

✅ Return false if continuation byte counter is not zero after processing all bytes

Assuming input integers are always 8-bit without masking

Incorrect bit checks if input has higher bits set

✅ Mask input with 0xFF or ensure input is within 0-255

🧠
Brute Force (Check Each Byte Individually with Nested Conditions)
💡 This approach exists to build intuition by explicitly checking each byte and its expected pattern without using bitmask tricks. It helps beginners understand the UTF-8 rules before optimizing.

Intuition

Check each byte one by one, determine how many bytes the current character should have based on the leading bits, then verify the following bytes are valid continuation bytes.

Algorithm

  1. Initialize an index to 0 to iterate over the data array.
  2. For each byte, determine the number of bytes in the current UTF-8 character by checking leading bits.
  3. Check if the following bytes are valid continuation bytes (start with '10').
  4. If any check fails, return false; if all pass, return true.
💡 The challenge is correctly identifying the number of bytes per character and validating continuation bytes, which requires careful bit checks.
</>
Code
def validUtf8(data):
    n = len(data)
    i = 0
    while i < n:
        byte = data[i]
        # Determine number of bytes
        if (byte >> 7) == 0:
            num_bytes = 1
        elif (byte >> 5) == 0b110:
            num_bytes = 2
        elif (byte >> 4) == 0b1110:
            num_bytes = 3
        elif (byte >> 3) == 0b11110:
            num_bytes = 4
        else:
            return False
        # Check continuation bytes
        if i + num_bytes > n:
            return False
        for j in range(i + 1, i + num_bytes):
            if (data[j] >> 6) != 0b10:
                return False
        i += num_bytes
    return True

# Driver code
if __name__ == '__main__':
    print(validUtf8([197, 130, 1]))  # True
    print(validUtf8([235, 140, 4]))  # False
Line Notes
while i < n:Loop over all bytes in the data array
if (byte >> 7) == 0:Check if the first bit is 0, meaning 1-byte character
elif (byte >> 5) == 0b110:Check if first three bits are 110, meaning 2-byte character
for j in range(i + 1, i + num_bytes):Verify each continuation byte starts with '10'
public class Solution {
    public boolean validUtf8(int[] data) {
        int n = data.length;
        int i = 0;
        while (i < n) {
            int byteVal = data[i];
            int numBytes;
            if ((byteVal >> 7) == 0) {
                numBytes = 1;
            } else if ((byteVal >> 5) == 0b110) {
                numBytes = 2;
            } else if ((byteVal >> 4) == 0b1110) {
                numBytes = 3;
            } else if ((byteVal >> 3) == 0b11110) {
                numBytes = 4;
            } else {
                return false;
            }
            if (i + numBytes > n) return false;
            for (int j = i + 1; j < i + numBytes; j++) {
                if ((data[j] >> 6) != 0b10) return false;
            }
            i += numBytes;
        }
        return true;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.validUtf8(new int[]{197, 130, 1})); // true
        System.out.println(sol.validUtf8(new int[]{235, 140, 4})); // false
    }
}
Line Notes
while (i < n) {Iterate through each byte in the input array
if ((byteVal >> 7) == 0) {Check if the byte is a single-byte character
for (int j = i + 1; j < i + numBytes; j++) {Check all continuation bytes for correct pattern
return false;Return false immediately if any validation fails
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    bool validUtf8(vector<int>& data) {
        int n = data.size();
        int i = 0;
        while (i < n) {
            int byteVal = data[i];
            int numBytes;
            if ((byteVal >> 7) == 0) {
                numBytes = 1;
            } else if ((byteVal >> 5) == 0b110) {
                numBytes = 2;
            } else if ((byteVal >> 4) == 0b1110) {
                numBytes = 3;
            } else if ((byteVal >> 3) == 0b11110) {
                numBytes = 4;
            } else {
                return false;
            }
            if (i + numBytes > n) return false;
            for (int j = i + 1; j < i + numBytes; j++) {
                if ((data[j] >> 6) != 0b10) return false;
            }
            i += numBytes;
        }
        return true;
    }
};

int main() {
    Solution sol;
    vector<int> data1 = {197, 130, 1};
    vector<int> data2 = {235, 140, 4};
    cout << boolalpha << sol.validUtf8(data1) << endl; // true
    cout << boolalpha << sol.validUtf8(data2) << endl; // false
    return 0;
}
Line Notes
while (i < n) {Loop through all bytes in the vector
if ((byteVal >> 7) == 0) {Check if the byte is a single-byte UTF-8 character
for (int j = i + 1; j < i + numBytes; j++) {Validate continuation bytes start with '10'
return false;Immediately return false if any byte fails validation
var validUtf8 = function(data) {
    let n = data.length;
    let i = 0;
    while (i < n) {
        let byte = data[i];
        let numBytes;
        if ((byte >> 7) === 0) {
            numBytes = 1;
        } else if ((byte >> 5) === 0b110) {
            numBytes = 2;
        } else if ((byte >> 4) === 0b1110) {
            numBytes = 3;
        } else if ((byte >> 3) === 0b11110) {
            numBytes = 4;
        } else {
            return false;
        }
        if (i + numBytes > n) return false;
        for (let j = i + 1; j < i + numBytes; j++) {
            if ((data[j] >> 6) !== 0b10) return false;
        }
        i += numBytes;
    }
    return true;
};

// Test cases
console.log(validUtf8([197, 130, 1])); // true
console.log(validUtf8([235, 140, 4])); // false
Line Notes
while (i < n) {Iterate over each byte in the input array
if ((byte >> 7) === 0) {Check if the byte is a single-byte UTF-8 character
for (let j = i + 1; j < i + numBytes; j++) {Check that continuation bytes start with '10'
return false;Return false immediately if any byte does not match UTF-8 pattern
⏱
Complexity
TimeO(n)
SpaceO(1)

We scan the array once, checking each byte and its continuation bytes in constant time per character.

💡 For n=100,000 bytes, this means roughly 100,000 operations, which is efficient for interview constraints.
Interview Verdict: Accepted

This approach is straightforward and efficient enough to pass all tests, making it a solid baseline solution.

🧠
Bitmasking with Predefined Masks for Leading Bytes
💡 This approach uses bitmasks to cleanly identify the number of bytes in a character, improving readability and reducing error-prone comparisons.

Intuition

Use masks to isolate leading bits and compare against known UTF-8 patterns to determine character length, then verify continuation bytes similarly.

Algorithm

  1. Define masks and expected patterns for 1 to 4 byte UTF-8 characters.
  2. For each byte, apply masks to determine the character length.
  3. Check if the following bytes are valid continuation bytes using bitmask.
  4. Return false if any check fails; otherwise, return true.
💡 Using masks abstracts away bit shifts and makes the code easier to verify and extend.
</>
Code
def validUtf8(data):
    masks = [0b10000000, 0b11100000, 0b11110000, 0b11111000]
    patterns = [0b00000000, 0b11000000, 0b11100000, 0b11110000]
    n = len(data)
    i = 0
    while i < n:
        byte = data[i]
        num_bytes = 0
        for idx in range(4):
            if (byte & masks[idx]) == patterns[idx]:
                num_bytes = idx + 1
                break
        if num_bytes == 0 or num_bytes > 4:
            return False
        if i + num_bytes > n:
            return False
        for j in range(i + 1, i + num_bytes):
            if (data[j] & 0b11000000) != 0b10000000:
                return False
        i += num_bytes
    return True

# Driver code
if __name__ == '__main__':
    print(validUtf8([197, 130, 1]))  # True
    print(validUtf8([235, 140, 4]))  # False
Line Notes
masks = [0b10000000, 0b11100000, 0b11110000, 0b11111000]Masks isolate leading bits for 1-4 byte characters
patterns = [0b00000000, 0b11000000, 0b11100000, 0b11110000]Expected bit patterns for each character length
if (byte & masks[idx]) == patterns[idx]:Check if byte matches the pattern for this character length
if (data[j] & 0b11000000) != 0b10000000:Verify continuation bytes start with '10'
public class Solution {
    public boolean validUtf8(int[] data) {
        int[] masks = {0b10000000, 0b11100000, 0b11110000, 0b11111000};
        int[] patterns = {0b00000000, 0b11000000, 0b11100000, 0b11110000};
        int n = data.length;
        int i = 0;
        while (i < n) {
            int byteVal = data[i];
            int numBytes = 0;
            for (int idx = 0; idx < 4; idx++) {
                if ((byteVal & masks[idx]) == patterns[idx]) {
                    numBytes = idx + 1;
                    break;
                }
            }
            if (numBytes == 0 || numBytes > 4) return false;
            if (i + numBytes > n) return false;
            for (int j = i + 1; j < i + numBytes; j++) {
                if ((data[j] & 0b11000000) != 0b10000000) return false;
            }
            i += numBytes;
        }
        return true;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.validUtf8(new int[]{197, 130, 1})); // true
        System.out.println(sol.validUtf8(new int[]{235, 140, 4})); // false
    }
}
Line Notes
int[] masks = {0b10000000, 0b11100000, 0b11110000, 0b11111000};Masks for isolating leading bits
int[] patterns = {0b00000000, 0b11000000, 0b11100000, 0b11110000};Expected patterns for each UTF-8 character length
if ((byteVal & masks[idx]) == patterns[idx]) {Check if byte matches a valid UTF-8 leading pattern
if ((data[j] & 0b11000000) != 0b10000000) return false;Check continuation bytes start with '10'
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    bool validUtf8(vector<int>& data) {
        int masks[4] = {0b10000000, 0b11100000, 0b11110000, 0b11111000};
        int patterns[4] = {0b00000000, 0b11000000, 0b11100000, 0b11110000};
        int n = data.size();
        int i = 0;
        while (i < n) {
            int byteVal = data[i];
            int numBytes = 0;
            for (int idx = 0; idx < 4; idx++) {
                if ((byteVal & masks[idx]) == patterns[idx]) {
                    numBytes = idx + 1;
                    break;
                }
            }
            if (numBytes == 0 || numBytes > 4) return false;
            if (i + numBytes > n) return false;
            for (int j = i + 1; j < i + numBytes; j++) {
                if ((data[j] & 0b11000000) != 0b10000000) return false;
            }
            i += numBytes;
        }
        return true;
    }
};

int main() {
    Solution sol;
    vector<int> data1 = {197, 130, 1};
    vector<int> data2 = {235, 140, 4};
    cout << boolalpha << sol.validUtf8(data1) << endl; // true
    cout << boolalpha << sol.validUtf8(data2) << endl; // false
    return 0;
}
Line Notes
int masks[4] = {0b10000000, 0b11100000, 0b11110000, 0b11111000};Masks to isolate leading bits for UTF-8 bytes
int patterns[4] = {0b00000000, 0b11000000, 0b11100000, 0b11110000};Expected bit patterns for each character length
if ((byteVal & masks[idx]) == patterns[idx]) {Check if the byte matches a valid UTF-8 leading byte pattern
if ((data[j] & 0b11000000) != 0b10000000) return false;Verify continuation bytes start with '10'
var validUtf8 = function(data) {
    const masks = [0b10000000, 0b11100000, 0b11110000, 0b11111000];
    const patterns = [0b00000000, 0b11000000, 0b11100000, 0b11110000];
    let n = data.length;
    let i = 0;
    while (i < n) {
        let byte = data[i];
        let numBytes = 0;
        for (let idx = 0; idx < 4; idx++) {
            if ((byte & masks[idx]) === patterns[idx]) {
                numBytes = idx + 1;
                break;
            }
        }
        if (numBytes === 0 || numBytes > 4) return false;
        if (i + numBytes > n) return false;
        for (let j = i + 1; j < i + numBytes; j++) {
            if ((data[j] & 0b11000000) !== 0b10000000) return false;
        }
        i += numBytes;
    }
    return true;
};

// Test cases
console.log(validUtf8([197, 130, 1])); // true
console.log(validUtf8([235, 140, 4])); // false
Line Notes
const masks = [0b10000000, 0b11100000, 0b11110000, 0b11111000];Masks to isolate leading bits for UTF-8 bytes
const patterns = [0b00000000, 0b11000000, 0b11100000, 0b11110000];Expected bit patterns for each UTF-8 character length
if ((byte & masks[idx]) === patterns[idx]) {Check if the byte matches a valid UTF-8 leading byte pattern
if ((data[j] & 0b11000000) !== 0b10000000) return false;Verify continuation bytes start with '10'
⏱
Complexity
TimeO(n)
SpaceO(1)

We iterate through the array once, using bitmask operations which are constant time.

💡 For large inputs, this approach is just as efficient as brute force but easier to maintain.
Interview Verdict: Accepted

This approach is preferred for clarity and maintainability while maintaining optimal performance.

🧠
Single Pass with Continuation Byte Counter
💡 This approach optimizes by tracking how many continuation bytes are expected, reducing repeated pattern checks.

Intuition

Use a counter to track how many continuation bytes are needed after a leading byte, decrementing it as continuation bytes are validated.

Algorithm

  1. Initialize a counter for expected continuation bytes to 0.
  2. Iterate over each byte in the data array.
  3. If counter is 0, determine the number of bytes in the character from leading bits and set counter accordingly.
  4. If counter > 0, check if the byte is a valid continuation byte and decrement counter.
  5. If any check fails or counter is not zero at the end, return false; else return true.
💡 This approach simplifies validation by linearizing the checks and avoiding nested loops.
</>
Code
def validUtf8(data):
    remaining = 0
    for byte in data:
        if remaining == 0:
            if (byte >> 5) == 0b110:
                remaining = 1
            elif (byte >> 4) == 0b1110:
                remaining = 2
            elif (byte >> 3) == 0b11110:
                remaining = 3
            elif (byte >> 7) == 0:
                remaining = 0
            else:
                return False
        else:
            if (byte >> 6) != 0b10:
                return False
            remaining -= 1
    return remaining == 0

# Driver code
if __name__ == '__main__':
    print(validUtf8([197, 130, 1]))  # True
    print(validUtf8([235, 140, 4]))  # False
Line Notes
remaining = 0Tracks how many continuation bytes are expected
if remaining == 0:If no continuation bytes expected, determine character length
elif (byte >> 4) == 0b1110:Check for 3-byte character leading bits
if (byte >> 6) != 0b10:Validate continuation byte pattern
public class Solution {
    public boolean validUtf8(int[] data) {
        int remaining = 0;
        for (int byteVal : data) {
            if (remaining == 0) {
                if ((byteVal >> 5) == 0b110) {
                    remaining = 1;
                } else if ((byteVal >> 4) == 0b1110) {
                    remaining = 2;
                } else if ((byteVal >> 3) == 0b11110) {
                    remaining = 3;
                } else if ((byteVal >> 7) == 0) {
                    remaining = 0;
                } else {
                    return false;
                }
            } else {
                if ((byteVal >> 6) != 0b10) return false;
                remaining--;
            }
        }
        return remaining == 0;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.validUtf8(new int[]{197, 130, 1})); // true
        System.out.println(sol.validUtf8(new int[]{235, 140, 4})); // false
    }
}
Line Notes
int remaining = 0;Counter for expected continuation bytes
if (remaining == 0) {Determine character length when no continuation bytes expected
else { if ((byteVal >> 6) != 0b10) return false;Validate continuation byte pattern
remaining--;Decrement continuation byte counter after validation
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    bool validUtf8(vector<int>& data) {
        int remaining = 0;
        for (int byteVal : data) {
            if (remaining == 0) {
                if ((byteVal >> 5) == 0b110) {
                    remaining = 1;
                } else if ((byteVal >> 4) == 0b1110) {
                    remaining = 2;
                } else if ((byteVal >> 3) == 0b11110) {
                    remaining = 3;
                } else if ((byteVal >> 7) == 0) {
                    remaining = 0;
                } else {
                    return false;
                }
            } else {
                if ((byteVal >> 6) != 0b10) return false;
                remaining--;
            }
        }
        return remaining == 0;
    }
};

int main() {
    Solution sol;
    vector<int> data1 = {197, 130, 1};
    vector<int> data2 = {235, 140, 4};
    cout << boolalpha << sol.validUtf8(data1) << endl; // true
    cout << boolalpha << sol.validUtf8(data2) << endl; // false
    return 0;
}
Line Notes
int remaining = 0;Tracks how many continuation bytes are expected
if (remaining == 0) {Determine the number of bytes for a new character
if ((byteVal >> 6) != 0b10) return false;Check if continuation byte starts with '10'
remaining--;Decrease the count of expected continuation bytes
var validUtf8 = function(data) {
    let remaining = 0;
    for (let byte of data) {
        if (remaining === 0) {
            if ((byte >> 5) === 0b110) {
                remaining = 1;
            } else if ((byte >> 4) === 0b1110) {
                remaining = 2;
            } else if ((byte >> 3) === 0b11110) {
                remaining = 3;
            } else if ((byte >> 7) === 0) {
                remaining = 0;
            } else {
                return false;
            }
        } else {
            if ((byte >> 6) !== 0b10) return false;
            remaining--;
        }
    }
    return remaining === 0;
};

// Test cases
console.log(validUtf8([197, 130, 1])); // true
console.log(validUtf8([235, 140, 4])); // false
Line Notes
let remaining = 0;Counter for how many continuation bytes are expected
if (remaining === 0) {When no continuation bytes expected, determine character length
if ((byte >> 6) !== 0b10) return false;Validate continuation byte pattern
remaining--;Decrement continuation byte counter after each valid continuation byte
⏱
Complexity
TimeO(n)
SpaceO(1)

Single pass through the data array with constant time checks per byte.

💡 This approach is the most efficient and clean for large inputs, minimizing overhead.
Interview Verdict: Accepted

This is the optimal approach to implement in interviews due to its simplicity and efficiency.

📊
All Approaches - One-Glance Tradeoffs
💡 The single pass approach with a continuation byte counter is recommended for interviews due to its clarity and efficiency.
ApproachTimeSpaceStack RiskReconstructUse In Interview
1. Brute ForceO(n)O(1)NoN/AGood to mention for clarity, but avoid coding due to verbosity
2. Bitmasking with Predefined MasksO(n)O(1)NoN/AGood for clean code, acceptable to code if comfortable with bitmasks
3. Single Pass with Continuation Byte CounterO(n)O(1)NoN/ABest approach to code in interviews for simplicity and efficiency
💼
Interview Strategy
💡 Use this guide to understand the problem deeply, practice multiple approaches, and prepare to explain your reasoning clearly in interviews.

How to Present

Step 1: Clarify the problem and UTF-8 encoding rules with the interviewer.Step 2: Present the brute force approach to show understanding of the problem.Step 3: Discuss improvements using bitmasking for cleaner code.Step 4: Present the optimal single pass approach with a continuation byte counter.Step 5: Write clean, tested code and explain edge cases.

Time Allocation

Clarify: 3min → Approach: 5min → Code: 10min → Test: 5min. Total ~23min

What the Interviewer Tests

The interviewer tests your understanding of bit manipulation, attention to detail in pattern matching, and ability to optimize code while maintaining correctness.

Common Follow-ups

  • How would you handle invalid input outside 0-255? → Validate input range before processing.
  • Can you extend this to UTF-16 validation? → Discuss differences in encoding and validation rules.
💡 Follow-ups often test your ability to generalize or handle edge cases beyond the initial problem.
🔍
Pattern Recognition

When to Use

1) Input involves byte sequences or arrays of integers representing bytes; 2) Need to validate encoding or bit patterns; 3) Problem mentions leading bits or continuation bytes; 4) Requires bit manipulation to check patterns.

Signature Phrases

leading bitscontinuation bytesbyte pattern check

NOT This Pattern When

Problems involving string parsing without bit-level checks or problems focused on arithmetic bit operations without pattern validation.

Similar Problems

Valid Parentheses - pattern matching of sequencesBinary Number with Alternating Bits - checking bit patternsNumber of 1 Bits - counting bits in integers

Practice

(1/5)
1. Consider the following code snippet implementing the optimal approach for bitwise AND of numbers range. What is the output when calling rangeBitwiseAnd(5, 7)?
easy
A. 4
B. 5
C. 0
D. 7

Solution

  1. Step 1: Trace initial values

    left = 5 (binary 0101), right = 7 (binary 0111)
  2. Step 2: Execute loop iterations

    First iteration: right = 7 & 6 = 6 (0110) Second iteration: right = 6 & 5 = 4 (0100) Now right (4) <= left (5) is true, loop ends.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Final returned value is 4 after clearing differing bits [OK]
Hint: Bit-clearing reduces right until common prefix found [OK]
Common Mistakes:
  • Confusing loop condition
  • Off-by-one in bit clearing
  • Returning right too early
2. Consider the following code to find the missing number in an array containing numbers from 0 to n with one missing. What is the value of xor_all just before the return statement when the input is [3, 0, 1]?
easy
A. 2
B. 3
C. 0
D. 1

Solution

  1. Step 1: Trace xor_all after first loop (XOR 0 to 3)

    0 ^ 0 = 0, 0 ^ 1 = 1, 1 ^ 2 = 3, 3 ^ 3 = 0
  2. Step 2: XOR xor_all with each array element

    0 ^ 3 = 3, 3 ^ 0 = 3, 3 ^ 1 = 2
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Final xor_all is 2, the missing number [OK]
Hint: XOR all indices and elements cancels pairs leaving missing number [OK]
Common Mistakes:
  • Off-by-one in range causing wrong xor_all
  • XORing only array or only indices
  • Misreading xor_all updates
3. What is the time complexity of the XOR approach to find the missing number in an array of length n containing numbers from 0 to n with one missing?
medium
A. O(n log n) due to sorting inside XOR operations
B. O(1) since XOR is a constant time operation
C. O(n^2) because XOR operations are nested
D. O(n) because it iterates over the range and array once each

Solution

  1. Step 1: Identify loops in the XOR approach

    There are two separate loops: one over range 0 to n, and one over the array of length n.
  2. Step 2: Calculate total time complexity

    Each loop runs O(n) times, so total time is O(n) + O(n) = O(n).
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    No nested loops or sorting, linear time confirmed [OK]
Hint: Two separate linear loops sum to O(n) time [OK]
Common Mistakes:
  • Confusing XOR operations as nested loops
  • Assuming sorting inside XOR
  • Ignoring linear iteration over range
4. What is the time complexity of generating an n-bit Gray code sequence using the optimal bitwise formula [i ^ (i >> 1) for i in range(1 << n)]?
medium
A. O(n)
B. O((2^n)!)
C. O(n * 2^n)
D. O(2^n)

Solution

  1. Step 1: Analyze the loop iteration count

    The list comprehension iterates over all integers from 0 to 2^n - 1, so 2^n iterations.
  2. Step 2: Analyze work per iteration

    Each iteration performs constant time bitwise operations (XOR and right shift), so O(1) per iteration.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Total time is proportional to 2^n, not multiplied by n or factorial [OK]
Hint: Loop runs 2^n times with O(1) work each [OK]
Common Mistakes:
  • Confusing n with 2^n and claiming O(n)
  • Assuming bitwise operations cost O(n)
  • Mistaking factorial complexity from brute force backtracking
5. What is the time complexity of the optimal bitmasking solution that sorts words by length and prunes pairs early when finding the maximum product of word lengths with no common letters?
medium
A. O(n^3) due to triple nested loops over words and characters
B. O(n^2 * k) because each pair requires checking all characters
C. O(n^2 + n*k + n log n) where n is number of words and k is average word length
D. O(n log n) since sorting dominates the runtime

Solution

  1. Step 1: Analyze preprocessing steps

    Computing bitmasks takes O(n*k) where k is average word length. Sorting masks by length takes O(n log n).
  2. Step 2: Analyze nested loops with pruning

    Nested loops run O(n^2) in worst case, but pruning reduces unnecessary checks. Bitwise AND checks are O(1).
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Combining all steps yields O(n^2 + n*k + n log n) [OK]
Hint: Bitmask checks are O(1), pruning reduces pairs [OK]
Common Mistakes:
  • Assuming O(n^2*k) due to character checks per pair
  • Ignoring sorting cost
  • Confusing recursion stack space with iterative solution
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard