jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
43 stars 5 forks source link

String encode and decode #197

Open jsartisan opened 2 hours ago

jsartisan commented 2 hours ago

Info

difficulty: medium
title: String encode and decode
type: question
template: typescript
tags: javascript, blind75

Question

Design an algorithm to encode a list of strings to a single string and decode it back to the original list of strings.

Constraints:

Examples:

// Example 1:
const input1 = ["neet", "code", "love", "you"];
const encoded1 = encode(input1);
console.log(decode(encoded1)); 
// Output: ["neet", "code", "love", "you"]

// Example 2:
const input2 = ["we", "say", ":", "yes"];
const encoded2 = encode(input2);
console.log(decode(encoded2));
// Output: ["we", "say", ":", "yes"]

Template

index.ts

export class Codec {
  encode(strs: string[]): string {}

  decode(s: string): string[] {}
}

index.test.ts

import { Codec } from "./index";

describe("Codec", () => {
  const codec = new Codec();

  test("Example 1: Basic encoding and decoding", () => {
    const input = ["neet", "code", "love", "you"];
    const encoded = codec.encode(input);
    const decoded = codec.decode(encoded);
    expect(decoded).toEqual(input);
  });

  test("Example 2: Strings with special characters", () => {
    const input = ["we", "say", ":", "yes"];
    const encoded = codec.encode(input);
    const decoded = codec.decode(encoded);
    expect(decoded).toEqual(input);
  });

  test("Empty array", () => {
    const input: string[] = [];
    const encoded = codec.encode(input);
    const decoded = codec.decode(encoded);
    expect(decoded).toEqual(input);
  });

  test("Array with empty strings", () => {
    const input = ["", "hello", ""];
    const encoded = codec.encode(input);
    const decoded = codec.decode(encoded);
    expect(decoded).toEqual(input);
  });

  test("Strings with numbers", () => {
    const input = ["123", "456", "789"];
    const encoded = codec.encode(input);
    const decoded = codec.decode(encoded);
    expect(decoded).toEqual(input);
  });
});
github-actions[bot] commented 2 hours ago

198 - Pull Request updated.