cswork / libraryOpen practice workspace

Coding questions · Amazon

Solve Algorithmic Challenges in Online Coding Assessments

This question evaluates proficiency in fundamental algorithmic problem-solving, specifically array manipulation, string processing, and the use of basic data structures along with performance and complexity reasoning.

Scenario

Online assessment requiring implementation of common algorithmic problems.

Question

Given an array of integers and a target, return indices of the two numbers that add up to the target (assume exactly one solution). 2) Given a string, determine the length of the longest substring without repeating characters.

Hints

Use hash maps for O(n) solutions; mind edge cases like empty input.

Two Sum

Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.

You may assume that each input has exactly one solution, and you may not use the same element twice. Return the answer as a list of the two indices [i, j] with i < j.

Example 1:

Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]  (because nums[0] + nums[1] == 9)

Example 2:

Input: nums = [3, 2, 4], target = 6
Output: [1, 2]

Use a hash map to achieve an O(n) single-pass solution.

Constraints

  • 2 <= len(nums) <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Exactly one valid answer exists.

Hints

  1. A brute-force O(n^2) approach checks every pair, but you can do better.
  2. As you iterate, store each number's index in a hash map.
  3. For each number, check whether target - number is already in the map; if so you have your pair.

Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring that contains no repeating characters.

A substring is a contiguous sequence of characters within the string.

Example 1:

Input: s = "abcabcbb"
Output: 3  (the answer is "abc", with length 3)

Example 2:

Input: s = "bbbbb"
Output: 1  (the answer is "b")

Example 3:

Input: s = "pwwkew"
Output: 3  (the answer is "wke"; note "pwke" is a subsequence, not a substring)

Use a sliding window with a hash map of last-seen indices for an O(n) solution.

Constraints

  • 0 <= len(s) <= 5 * 10^4
  • s consists of English letters, digits, symbols, and spaces.

Hints

  1. Maintain a sliding window [start, i] that always contains only unique characters.
  2. Track the most recent index where each character was seen in a hash map.
  3. When you encounter a repeat that lies inside the current window, jump start to one past its previous index.