Compress an IPv6 address (RFC 5952)

A free hard coding practice problem from networking. Solve it in JavaScript, TypeScript or Python and check your solution against fresh hidden tests — edge cases and random inputs — as often as you like.

Difficulty
Hard
Type
Function
Topic
Networking
Languages
JavaScript, TypeScript or Python

Problem

addr is a full IPv6 address: exactly 8 groups of 1–4 hex digits (any case) separated by colons, with no :: in it. Return its canonical text form (RFC 5952):
1. write every group in lowercase without leading zeros (a zero group becomes 0);
2. find the LONGEST run of consecutive zero groups that is at least 2 groups long (on a tie, the FIRST such run) and replace that whole run with ::;
3. a single zero group is never replaced by ::.

Examples of the result shape: 2001:db8::1, ::1, 1::, ::.

Function signature

// JavaScript
function compressIpv6(addr)

// TypeScript
function compressIpv6(addr: any): any

// Python
def compress_ipv6(addr):

Examples

  1. compressIpv6("2001:0DB8:0000:0000:0000:ff00:0042:8329") → "2001:db8::ff00:42:8329"
  2. compressIpv6("0000:0000:0000:0000:0000:0000:0000:0001") → "::1"
  3. compressIpv6("2001:db8:0:1:1:1:1:1") → "2001:db8:0:1:1:1:1:1"

How checking works

Run your code against the examples above, then submit a check: it runs on the server against hidden tests built fresh each time, including edge cases and random inputs. Practice is untimed and never affects a verified score; when you are ready, take a graded coding challenge to earn a badge.

More practice problems

Next steps