Codepath

Find the Expedition Log Concatenation Value

TIP102 Unit 3 Session 2 Standard (Click for link to problem statements)

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q: What is the input to the problem?
    • A: The input is a 0-indexed integer array logs, where each element represents a log entry.
  • Q: What is the output?
    • A: The output is the concatenation value of the logs after performing the specified operations until the logs array is empty.
  • Q: How are the concatenation operations performed?
    • A: If more than one log entry exists, concatenate the first and last log entries and add this value to the concatenation value, then remove these entries. If only one log entry exists, add its value to the concatenation value and remove it.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Use two pointers to manage the operations on the log entries: one starting at the beginning and the other at the end of the logs array. Concatenate the values as specified, update the concatenation value, and move the pointers inward until the array is empty.

1. Initialize a variable `conc_value` to 0 to store the concatenation value.
2. Initialize two pointers: `left` starting at 0 and `right` starting at the last index of the `logs` array.
3. While `left` is less than or equal to `right`:
   1. If `left` is equal to `right`, only one log entry remains, so add its value to `conc_value`.
   2. If `left` is not equal to `right`, concatenate the log entries at `left` and `right`, convert the result to an integer, and add it to `conc_value`.
   3. Move `left` one step to the right and `right` one step to the left.
4. Return the final value of `conc_value`.

⚠️ Common Mistakes

  • Incorrectly managing the case where only one log entry remains, leading to incorrect results.
  • Forgetting to update the left and right pointers correctly, which could result in an infinite loop or incorrect calculations.
  • Concatenating the log entries without converting them to a string first, leading to incorrect concatenation results.

I-mplement

def find_the_log_conc_val(logs):
    conc_value = 0
    left = 0
    right = len(logs) - 1
    
    while left <= right:
        if left == right:
            # If only one element remains
            conc_value += logs[left]
        else:
            # Concatenate first and last elements
            concat = int(str(logs[left]) + str(logs[right]))
            conc_value += concat
        
        # Move pointers inward
        left += 1
        right -= 1
    
    return conc_value

# Example usage
print(find_the_log_conc_val([7, 52, 2, 4]))  # Output: 596
print(find_the_log_conc_val([5, 14, 13, 8, 12]))  # Output: 673
Fork me on GitHub