AlgoMaster Logo
AlgoMasterEncode a Geohashmedium

Encode a Geohash

medium

A geohash encodes a latitude and longitude as a short string. Each additional character identifies a smaller cell, so nearby points often share a prefix that can be used by a spatial index.

Design a GeohashEncoder class:

  • GeohashEncoder() creates a stateless encoder.
  • string encode(double latitude, double longitude, int precision) returns exactly precision geohash characters.

Start with longitude range [-180, 180] and latitude range [-90, 90]. Generate bits by alternating dimensions, beginning with longitude. For the active range:

  • If the coordinate is at least the midpoint, emit 1 and keep the upper half.
  • Otherwise, emit 0 and keep the lower half.

Group every five bits from most significant to least significant and map values 0 through 31 through:

Each call starts from the full coordinate ranges.

Example 1:

Input:

Output:

Explanation: Twenty-five alternating range decisions encode San Francisco as 9q8yy.

Example 2:

Input:

Output:

Explanation: At precision 6, London's coordinate cell is represented by gcpvj0.

Constraints

  • -90 <= latitude <= 90
  • -180 <= longitude <= 180
  • 1 <= precision <= 12
  • Inputs are finite numbers.
  • At most 100 calls are made to encode.
Hints

Loading...
CallReturns
new GeohashEncoder()null
encode(37.7749, -122.4194, 5)"9q8yy"

San Francisco falls through 25 alternating longitude/latitude subdivisions to the five-character geohash 9q8yy.

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