Solve Two OA Coding Problems
Company: Salesforce
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: These two problems evaluate in-place array manipulation and run-length encoding implementation for character sequences, and algorithmic reasoning about integer operations and minimal-operation sequences, falling squarely within the Coding & Algorithms domain.
Part 1: In-Place Character Run Compression
Constraints
- 0 <= len(chars) <= 100000
- Each element of `chars` is a string of length 1
- The algorithm should run in linear time
- Only constant extra auxiliary space should be used
Examples
Input: (['a','a','a','b','b','c'],)
Expected Output: 5
Explanation: The list is compressed to `['a','3','b','2','c']`, so the new length is 5.
Input: (['a'],)
Expected Output: 1
Explanation: A single character stays unchanged.
Input: ([],)
Expected Output: 0
Explanation: An empty list remains empty.
Input: (['a','b','c'],)
Expected Output: 3
Explanation: There are no repeated consecutive characters, so the compressed form is the same.
Input: (['x','x','x','x','x','x','x','x','x','x','x','x'],)
Expected Output: 3
Explanation: Twelve `x` characters compress to `['x','1','2']`.
Hints
- Use one pointer to scan runs of equal characters and another pointer to write the compressed result.
- When a run length is greater than 1, convert the count to a string and write each digit separately.
Part 2: Minimum Operations to Reduce an Integer to Zero
Constraints
- 1 <= n <= 2147483647
- If `n` is even, the next value must be `n // 2`
- If `n` is odd, you may choose either `n + 1` or `n - 1`
- The solution should be efficient for large values of `n`
Examples
Input: (7,)
Expected Output: 5
Explanation: One optimal sequence is `7 -> 8 -> 4 -> 2 -> 1 -> 0`.
Input: (1,)
Expected Output: 1
Explanation: The only move is `1 -> 0`.
Input: (8,)
Expected Output: 4
Explanation: The sequence is `8 -> 4 -> 2 -> 1 -> 0`.
Input: (3,)
Expected Output: 3
Explanation: The optimal sequence is `3 -> 2 -> 1 -> 0`.
Input: (15,)
Expected Output: 6
Explanation: An optimal path is `15 -> 16 -> 8 -> 4 -> 2 -> 1 -> 0`.
Hints
- For an odd number, both choices make it even. Usually it is better to pick the one that creates more trailing zeros in binary.
- There is one important special case: when `n == 3`, subtracting 1 is better than adding 1.