875952. Encode and Decode Strings

Medium

Encode and Decode Strings

Slug: encode-and-decode-strings

Difficulty: Medium

Id: 875952

Topic Tags: Strings, Arrays

Company Tags: None

Summary

Given a string s and an integer n, we need to perform two operations:

  1. Encode: Replace each character in the string with its ASCII value multiplied by n.
  2. Decode: Reverse the encoding process.

This problem requires a basic understanding of strings, arrays, and mathematical operations.

Detailed Explanation

To solve this problem, we will create two separate functions: one for encoding and another for decoding.

Encoding Function The encoding function takes the input string s and integer n as parameters. It iterates through each character in the string, multiplies its ASCII value by n, and stores the result in a new array or string.

Here's the step-by-step breakdown:

  1. Create an empty array or string to store the encoded values.
  2. Iterate through each character in the input string using a loop (e.g., for-each or while-loop).
  3. For each character, multiply its ASCII value by n and add the result to the new array or string.
  4. Return the encoded array or string.

Decoding Function The decoding function takes the encoded array or string and integer n as parameters. It iterates through each element in the encoded array or string, divides its value by n, and stores the result in a new array or string.

Here's the step-by-step breakdown:

  1. Create an empty array or string to store the decoded values.
  2. Iterate through each element in the encoded array or string using a loop (e.g., for-each or while-loop).
  3. For each element, divide its value by n and add the result to the new array or string.
  4. Return the decoded array or string.

Time Complexity Analysis The time complexity of both encoding and decoding functions is O(n), where n is the length of the input string. This is because we are iterating through each character in the string once.

Space Complexity Analysis The space complexity of both encoding and decoding functions is also O(n), as we are creating a new array or string to store the encoded or decoded values.

Optimized Solutions

Java

View on GeeksforGeeks
public class EncodeDecode {
    public static String encode(String s, int n) {
        StringBuilder sb = new StringBuilder();
        for (char c : s.toCharArray()) {
            sb.append((int) c * n);
        }
        return sb.toString();
    }

    public static String decode(String s, int n) {
        StringBuilder sb = new StringBuilder();
        for (String str : s.split("")) {
            sb.append((char) Integer.parseInt(str) / n);
        }
        return sb.toString();
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.