AlgoMaster Logo
AlgoMasterCompute the Internet Checksummedium

Compute the Internet Checksum

medium

The Internet checksum protects IP, TCP, and UDP data against accidental corruption. It uses 16-bit one's-complement arithmetic, where overflow from the top of the word wraps around and is added at the bottom.

Design an InternetChecksumCalculator class:

  • InternetChecksumCalculator() creates a stateless calculator.
  • int checksum(int[] words) returns the Internet checksum of the supplied 16-bit words.

Compute the checksum in three steps:

  1. Add every word to a running sum that is wider than 16 bits.
  2. While the sum exceeds 0xFFFF, fold the carry with (sum & 0xFFFF) + (sum >> 16).
  3. Return the one's complement of the folded sum, masked to 16 bits.

Each call is independent.

Example 1:

Input:

Output:

Explanation: The words are 0x4500, 0x003C, and 0x1C46. They sum to 0x617E, whose 16-bit one's complement is 0x9E81, or 40573.

Example 2:

Input:

Output:

Explanation: The raw sum is 0x10000. Folding its carry produces 0x0001, and complementing that value produces 0xFFFE.

Constraints

  • 1 <= words.length <= 10^5
  • 0 <= words[i] <= 65535
  • Every value in words is an integer.
  • At most 100 calls are made to checksum.
Hints

Loading...
CallReturns
new InternetChecksumCalculator()null
checksum([17664,60,7238])40573

The words sum to 0x617E. No carry remains, and the 16-bit one's complement is 0x9E81, or 40573.

Run checks these cases. Submit also runs a larger hidden set.