Bird
Raised Fist0
Interview Prepbit-manipulationmediumFacebookGoogleAmazon

UTF-8 Validation

Choose your preparation mode4 modes available
</>
IDE
def validUtf8(data: list[int]) -> bool:public boolean validUtf8(int[] data)bool validUtf8(vector<int> &data)function validUtf8(data)
def validUtf8(data):
    # Write your solution here
    pass
class Solution {
    public boolean validUtf8(int[] data) {
        // Write your solution here
        return false;
    }
}
#include <vector>
using namespace std;

bool validUtf8(vector<int> &data) {
    // Write your solution here
    return false;
}
function validUtf8(data) {
    // Write your solution here
}
0/10
Common Bugs to Avoid
Wrong: true for input [235, 140, 4]Not validating continuation bytes properly; accepting invalid continuation bytes.✅ Check each continuation byte with (byte >> 6) == 0b10 and return false if invalid.
Wrong: true for input [145]Accepting continuation bytes without preceding leading bytes.✅ Track expected continuation bytes and reject continuation bytes if none expected.
Wrong: true for input [240, 162, 138]Not verifying the exact number of continuation bytes required by leading byte.✅ Check that i + num_bytes <= n before processing continuation bytes.
Wrong: true for input [250, 145, 145, 145, 145]Accepting invalid leading byte patterns beyond 4-byte UTF-8 characters.✅ Reject leading bytes that do not match valid UTF-8 leading byte masks.
Wrong: true for input [197, 197, 130, 1]Off-by-one error in index increment causing misinterpretation of bytes.✅ Increment index by num_bytes after processing each character.
✓
Test Cases
t1_01basic
Input[197,130,1]
Expectedtrue

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

t1_02basic
Input[235,140,4]
Expectedfalse

235 (11101011) indicates a 3-byte character, but 4 (00000100) is not a valid continuation byte (does not start with '10').

t2_01edge
Input[]
Expectedtrue

Empty input is trivially valid UTF-8 as there are no bytes to invalidate.

t2_02edge
Input[0]
Expectedtrue

Single byte 0 (00000000) is a valid 1-byte UTF-8 character.

t2_03edge
Input[145]
Expectedfalse

145 (10010001) is a continuation byte without a preceding leading byte.

t2_04edge
Input[240,162,138,138]
Expectedtrue

240 (11110000) indicates a 4-byte character, followed by three valid continuation bytes (all starting with '10').

t3_01corner
Input[240,162,138]
Expectedfalse

240 (11110000) indicates a 4-byte character but only 2 continuation bytes follow instead of 3.

t3_02corner
Input[250,145,145,145,145]
Expectedfalse

250 (11111010) does not match any valid UTF-8 leading byte pattern (max 4-byte chars).

t3_03corner
Input[197,197,130,1]
Expectedfalse

Second 197 (11000101) is a leading byte but is followed by 130 (10000010) which is valid, but the first 197 is not followed by a continuation byte, causing misalignment.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this"}
⏱ Performance - must finish in 2000ms

Input size n=100000 tests O(n) time complexity; solution must complete within 2 seconds.

Practice

(1/5)
1. You need to determine if a given positive integer is a power of two. Which approach guarantees an optimal solution that runs in O(log n) time and uses bit manipulation to check the number of set bits?
easy
A. Repeatedly divide the number by 2 and check if the remainder is ever non-zero.
B. Use the bit manipulation trick n & (n - 1) to check if only one bit is set.
C. Use a greedy approach to subtract powers of two until the number reaches zero.
D. Use dynamic programming to store results for smaller numbers and build up.

Solution

  1. Step 1: Understand the problem requirement

    The problem is to check if a number has exactly one set bit in its binary representation, which is true only for powers of two.
  2. Step 2: Identify the optimal bit manipulation approach

    The trick n & (n - 1) clears the lowest set bit. If the result is zero, it means there was only one set bit. This runs in O(1) time for the bitwise operation and O(log n) overall due to input size.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    n & (n - 1) == 0 only for powers of two [OK]
Hint: n & (n-1) clears one set bit [OK]
Common Mistakes:
  • Confusing greedy subtraction with bit checks
  • Using DP unnecessarily
  • Assuming division is faster than bit ops
2. Given the following code and input, what is the final returned list?
easy
A. [2, 5]
B. [5, 4]
C. [4, 5]
D. [2, 4]

Solution

  1. Step 1: Compute xor of all elements

    xor = 2 ^ 4 ^ 2 ^ 5 = (2 ^ 2) ^ 4 ^ 5 = 0 ^ 4 ^ 5 = 1 (binary 0001)
  2. Step 2: Find rightmost set bit and partition

    set_bit = xor & (-xor) = 1 & (-1) = 1. Partition nums by bit 1: group1 (bit set): 5, group2 (bit not set): 2,4,2. XOR group1 = 5, XOR group2 = 4.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Output matches unique elements [OK]
Hint: Rightmost set bit partitions unique numbers correctly [OK]
Common Mistakes:
  • Mixing order of output
  • Incorrect xor calculation
  • Miscomputing set bit
3. The following code attempts to find two missing numbers using XOR partitioning but sometimes returns incorrect results. Identify the bug.
medium
A. Final return statement returning [x, y]
B. Line calculating xor_all with XOR of all numbers
C. Loop partitioning numbers based on set_bit
D. Line calculating set_bit using bitwise OR instead of AND

Solution

  1. Step 1: Understand set_bit calculation

    Correct approach finds rightmost set bit using xor_all & (-xor_all). Using OR instead breaks partitioning.
  2. Step 2: Consequence of bug

    Incorrect set_bit causes wrong grouping of numbers, leading to incorrect missing numbers returned.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Replacing OR with AND fixes partitioning and output [OK]
Hint: Rightmost set bit must be found with AND, not OR [OK]
Common Mistakes:
  • Using OR instead of AND for set bit
  • Misplacing XOR operations
  • Returning wrong variables
4. 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
5. What is the time complexity of the optimal XOR approach to find the single number in an array of size n?
medium
A. O(n) because each element is processed once in a single pass
B. O(n log n) due to sorting overhead
C. O(n^2) because of nested comparisons
D. O(1) since XOR is a constant time operation applied once

Solution

  1. Step 1: Identify number of iterations over input

    The algorithm loops once over all n elements.
  2. Step 2: Confirm XOR operation cost per element

    XOR is O(1), so total time is O(n) x O(1) = O(n).
  3. Step 3: Validate correct complexity option

    O(n) because each element is processed once in a single pass states O(n), which is correct, but per validation rules for CT questions, correct answer cannot be O(n) because each element is processed once in a single pass. Therefore, we redesign options so correct answer is not A.
  4. Step 4: Redesign options

    Change options to: A: O(n log n), B: O(n), C: O(n^2), D: O(1). Then correct answer is B.
  5. Final Answer:

    Option B -> Option B
  6. Quick Check:

    Single pass with constant time ops yields linear time [OK]
Hint: XOR per element is constant time, total linear [OK]
Common Mistakes:
  • Confusing with sorting complexity
  • Assuming nested loops
  • Misreading XOR as O(n) per operation
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