MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Range Sum Queries with Explanation

PHP Medium PHP Arrays 23 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around querie, line, range. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Answer q range-sum queries on an array.

Input Format

Line1 n q. Line2 n ints. Next q lines l r (0-based).

Output Format

q lines sums.

Constraints

n,q

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php $inputText=rtrim(stream_get_contents(STDIN)); if($inputText==='') exit; $inputLines=preg_split('/\\R/', $inputText); $first=preg_split('/\\s+/', trim($inputLines[0] ?? '')); $n=intval($first[0] ?? 0); $q=intval($first[1] ?? 0); $a=array_map('intval',preg_split('/\\s+/', trim($inputLines[1] ?? ''))); $pref=[0]; for($i=0;$i<$n;$i++) $pref[$i+1]=$pref[$i]+($a[$i] ?? 0); $output=[]; for($i=0;$i<$q;$i++){ $tokens=preg_split('/\\s+/', trim($inputLines[$i+2] ?? '')); $l=intval($tokens[0] ?? 0); $r=intval($tokens[1] ?? -1); $output[] = strval($pref[$r+1]-$pref[$l]); } echo implode(PHP_EOL,$output); ?>

Output Example

Input:
5 3 1 2 3 4 5 0 2 1 3 2 4
Output:
6 9 12

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next