Scanline Algorithm With Example
1 . Brute Force Approach :
Time Complexity : O(n) * O(qn) = O(qn)
Where,
2. Optimized Approach :
Time Complexity : O(n) + O(n+1) + (2*q) = O(n)
Where ,
Example :
Input : 6
1 2 3 4 5 6
3
1 4 2
2 3 3
0 4 1
Output: 2 5 9 10 9 6
We take Original array of size '6'
Recommended by LinkedIn
1 2 3 4 5 6
We take Dummy array of size '6+1', initially all are '0' values.
0 0 0 0 0 0 0
0 2 0 0 0 -2 0
Same repeat for all the queries
// For 2nd query, start_index = 2 and end_index = 3, also value = 3
0 2 3 0 -3 -2 0
// For 3rd query, start_index = 0 and end_index = 4, also value = 1
1 2 3 0 -3 -3 0
Do prefix sum/cumulative sum for all array elements
1 3 6 6 4 1 0
Now, add both original array and dummy array
1 2 3 4 5 6 --->Original Array
1 3 6 6 4 0 0 --->Dummy Array
2 5 9 10 9 6 --->Output Array
#newsletter #algorithm