Scanline Algorithm With Example
Sidramaraddy ??
Senior Full Stack Developer(React/Node.js) | MERN Stack Specialist | Building Scalable Apps | Expertise in REST APIs, MongoDB, and Firebase | 2+ Years in Web & App Development | Passionate Problem Solver
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'
领英推荐
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
Senior Full Stack Developer(React/Node.js) | MERN Stack Specialist | Building Scalable Apps | Expertise in REST APIs, MongoDB, and Firebase | 2+ Years in Web & App Development | Passionate Problem Solver
1 年#newsletter #algorithm