148. Array Range Update Queries

Asked in

Array Range Update Queries
You are given an array arr of size n and q queries.

Each query updates all elements from index l to index r to value k.

Return the final state of the array after processing all queries in order.

There are two variations:
  • All queries use the same value k.
  • Different queries may use different values k.

Method Signatures

Same k for all queries

List<Integer> updateArrayWithSameK(List<Integer> arr, List<String> ranges, int k)
  • arr is the initial array.
  • Each string in ranges is in the format "l,r".
  • For every range, update all indices from l to r to the same value k.
  • Return the final state of the array after all updates.

Different k for different queries

List<Integer> updateArray(List<Integer> arr, List<String> queries)
  • arr is the initial array.
  • Each string in queries is in the format "l,r,k".
  • For each query, update all indices from l to r to value k.
  • Return the final state of the array after all queries are processed in order.

Constraints

  • 1 ≤ n ≤ 10^5
  • 1 ≤ q ≤ 10^5
  • 0 ≤ l ≤ r < n
  • arr.size() = n
  • All queries are valid.
  • Process queries in the given order.
  • You must never use null as a parameter value.

Notes

  • If multiple queries update the same index, the later query overwrites the earlier value.
  • The final array depends on the order of the queries.
  • For the same k variation, every update uses the exact same value k.
  • For the different k variation, each query may use its own value k.

Examples

Example 1: Same k for all queries

updateArrayWithSameK(arr = [1, 2, 3, 4, 5], ranges = ["1,3", "0,1"], k = 9)
Returns [9, 9, 9, 9, 5]

Explanation:
  • After range "1,3", array becomes [1, 9, 9, 9, 5].
  • After range "0,1", array becomes [9, 9, 9, 9, 5].

Example 2: Different k for different queries

updateArray(arr = [1, 2, 3, 4, 5], queries = ["1,3,7", "2,4,0"])
Returns [1, 7, 0, 0, 0]

Explanation:
  • After query "1,3,7", array becomes [1, 7, 7, 7, 5].
  • After query "2,4,0", array becomes [1, 7, 0, 0, 0].

Example 3: Full array update

updateArray(arr = [5, 5, 5], queries = ["0,2,1"])
Returns [1, 1, 1]

Example 4: Single index updates

updateArray(arr = [4, 8, 6], queries = ["1,1,3", "2,2,9"])
Returns [4, 3, 9]




Please use Laptop/Desktop or any other large screen to add/edit code.