713596. Apple Sequences

Medium

Apple Sequences

Slug: apple-sequences--170646

Difficulty: Medium

Id: 713596

Topic Tags: two-pointer-algorithm, implementation, Algorithms

Company Tags: Ola Cabs

Summary

The Apple Sequences problem involves manipulating a given array of integers to produce a new sequence where each element is the product of the previous two elements. The goal is to design an efficient algorithm that can generate this sequence while minimizing time complexity.

Detailed Explanation

To solve this problem, we can utilize the Two-Pointer Algorithm approach. We'll maintain two pointers, prev and curr, which will keep track of the previous and current elements in the array. Our goal is to create a new sequence where each element is the product of the previous two elements.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty list result to store the final sequence.
  2. Set prev to the first element of the input array and curr to the second element.
  3. Calculate the product of prev and curr, which will be the first element in the new sequence. Add this to result.
  4. Move the pointers one step forward: increment prev to curr and update curr to the next element in the array.
  5. Repeat steps 3-4 until we reach the end of the input array.
  6. Return the generated sequence result.

Here's an ASCII art diagram illustrating the process:

input: [2, 3, 4]
prev | curr
---|---
2    | 3    (initial)
result: [6]

move pointers forward:
prev | curr
---|---
3    | 4    (new prev and curr)
calculate product: 3 * 4 = 12
add to result: [6, 12]
...

Time complexity analysis:

  • The algorithm iterates through the input array once, so the time complexity is O(n), where n is the length of the input array.
  • The space complexity is O(1) since we only use a constant amount of extra memory to store the result list.

Optimized Solutions

Java

View on GeeksforGeeks
public int[] appleSequences(int[] arr) {
    int[] result = new int[arr.length - 1];
    int prev = arr[0] * arr[1];
    for (int i = 2; i < arr.length; i++) {
        result[i - 2] = prev;
        prev = arr[i - 1] * arr[i];
    }
    return result;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.