 1596631020

# Sum of prime numbers in range [L, R] from given Array for Q queries

Given an array arr[] of the size of N followed by an array of Q queries, of the following two types:

• Query Type 1: Given two integers L and R, find the sum of prime elements from index L to R where 0 <= L <= R <= N-1.
• Query Type 2: Given two integers i and X, change arr[i] = X where 0 <= i <= n-1.

Note:_ Every first index of the subquery determines the type of query to be answered._

**Example: **

_Input: _arr[] = {1, 3, 5, 7, 9, 11}, Q = { { 1, 1, 3}, {2, 1, 10}, {1, 1, 3 } }

_Output: _

15

12

_Explanation: _

First query is of type 1, so answer is (3 + 5 + 7), = 15

Second query is of type 2, so arr = 10

Third query is of type 1, where arr = 10, which is not prime hence answer is (5 + 7) = 12

Input:_ arr[] = {1, 2, 35, 7, 14, 11}, Q = { {2, 4, 3}, {1, 4, 5 } }_

Output:_ 14_

Explanation:

First query is of type 2, So update arr = 3

Second query is of type 1, since arr = 3, which is prime. So answer is (3 + 11) = 14

**Naive Approach: **The idea is to iterate for each query between L to R and perform the required operation on the given array.

_Time Complexity: _O(Q * N * (O(sqrt(max(arr[i]))

**Approach: ** To optimize the problem use Segment tree and Sieve Of Eratosthenes.

• First, create a boolean array that will mark the prime numbers.
• Now while making the segment tree only add those array elements as leaf nodes which are prime.
• C++
• Python3

`// C++ program for the above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`**int**` `**const**` `MAX = 1000001;`

`**bool**` `prime[MAX];`

`// Function to find the prime numbers`

`**void**` `SieveOfEratosthenes()`

`{`

`// Create a boolean array prime[]`

`// and initialize all entries it as true`

`// A value in prime[i] will`

`// finally be false if i is Not a prime`

`**memset**``(prime,` `**true**``,` `**sizeof**``(prime));`

`**for**` `(``**int**` `p = 2; p * p <= MAX; p++) {`

`// Check if prime[p] is not`

`// changed, then it is a prime`

`**if**` `(prime[p] ==` `**true**``) {`

`// Update all multiples of p`

`// greater than or equal to`

`// the square of it numbers`

`// which are multiple of p`

`// and are less than p^2 are`

`// already been marked`

`**for**` `(``**int**` `i = p * p; i <= MAX; i += p)`

`prime[i] =` `**false**``;`

`}`

`}`

`}`

`// Function to get the middle`

`// index from corner indexes`

`**int**` `getMid(``**int**` `s,` `**int**` `e)`

`{`

`**return**` `s + (e - s) / 2;`

`}`

`// Function to get the sum of`

`// values in the given range`

`// of the array`

`**int**` `getSumUtil(``**int**``* st,` `**int**` `ss,`

`**int**` `se,` `**int**` `qs,`

`**int**` `qe,` `**int**` `si)`

`{`

`// If segment of this node is a`

`// part of given range, then`

`// return the sum of the segment`

`**if**` `(qs <= ss && qe >= se)`

`**return**` `st[si];`

`// If segment of this node is`

`// outside the given range`

`**if**` `(se < qs || ss > qe)`

`**return**` `0;`

`// If a part of this segment`

`// overlaps with the given range`

`**int**` `mid = getMid(ss, se);`

`**return**` `getSumUtil(st, ss, mid,`

`qs, qe,`

`2 * si + 1)`

`+ getSumUtil(st, mid + 1,`

`se, qs, qe,`

`2 * si + 2);`

`}`

`// Function to update the nodes which`

`// have the given index in their range`

`**void**` `updateValueUtil(``**int**``* st,` `**int**` `ss,`

`**int**` `se,` `**int**` `i,`

`**int**` `diff,` `**int**` `si)`

`{`

`// If the input index lies`

`// outside the range of`

`// this segment`

`**if**` `(i < ss || i > se)`

`**return**``;`

`// If the input index is in`

`// range of this node, then update`

`// the value of the node and its children`

`st[si] = st[si] + diff;`

`**if**` `(se != ss) {`

`**int**` `mid = getMid(ss, se);`

`updateValueUtil(st, ss, mid, i,`

`diff, 2 * si + 1);`

`updateValueUtil(st, mid + 1,`

`se, i, diff,`

`2 * si + 2);`

`}`

`}`

`// Function to update a value in`

`// input array and segment tree`

`**void**` `updateValue(``**int**` `arr[],` `**int**``* st,`

`**int**` `n,` `**int**` `i,`

`**int**` `new_val)`

`{`

`// Check for erroneous input index`

`**if**` `(i < 0 || i > n - 1) {`

`cout <<` `"-1"``;`

`**return**``;`

`}`

`// Get the difference between`

`// new value and old value`

`**int**` `diff = new_val - arr[i];`

`**int**` `prev_val = arr[i];`

`// Update the value in array`

`arr[i] = new_val;`

`// Update the values of`

`// nodes in segment tree`

`// only if either previous`

`// value or new value`

`// or both are prime`

`**if**` `(prime[new_val]`

`|| prime[prev_val]) {`

`// If only new value is prime`

`**if**` `(!prime[prev_val])`

`updateValueUtil(st, 0, n - 1,`

`i, new_val, 0);`

`// If only new value is prime`

`**else**` `**if**` `(!prime[new_val])`

`updateValueUtil(st, 0, n - 1,`

`i, -prev_val, 0);`

`// If both are prime`

`**else**`

`updateValueUtil(st, 0, n - 1,`

`i, diff, 0);`

`}`

`}`

`// Return sum of elements in range`

`// from index qs (quey start) to qe`

`// (query end). It mainly uses getSumUtil()`

`**int**` `getSum(``**int**``* st,` `**int**` `n,` `**int**` `qs,` `**int**` `qe)`

`{`

`// Check for erroneous input values`

`**if**` `(qs < 0 || qe > n - 1 || qs > qe) {`

`cout <<` `"-1"``;`

`**return**` `-1;`

`}`

`**return**` `getSumUtil(st, 0, n - 1,`

`qs, qe, 0);`

`}`

`// Function that constructs Segment Tree`

`**int**` `constructSTUtil(``**int**` `arr[],` `**int**` `ss,`

`**int**` `se,` `**int**``* st,`

`**int**` `si)`

`{`

`// If there is one element in`

`// array, store it in current node of`

`// segment tree and return`

`**if**` `(ss == se) {`

`// Only add those elements in segment`

`// tree which are prime`

`**if**` `(prime[arr[ss]])`

`st[si] = arr[ss];`

`**else**`

`st[si] = 0;`

`**return**` `st[si];`

`}`

`// If there are more than one`

`// elements, then recur for left and`

`// right subtrees and store the`

`// sum of values in this node`

`**int**` `mid = getMid(ss, se);`

`st[si]`

`= constructSTUtil(arr, ss, mid,`

`st, si * 2 + 1)`

`+ constructSTUtil(arr, mid + 1,`

`se, st,`

`si * 2 + 2);`

`**return**` `st[si];`

`}`

`// Function to construct segment`

`// tree from given array`

`**int**``* constructST(``**int**` `arr[],` `**int**` `n)`

`{`

`// Allocate memory for the segment tree`

`// Height of segment tree`

`**int**` `x = (``**int**``)(``**ceil**``(log2(n)));`

`// Maximum size of segment tree`

`**int**` `max_size = 2 * (``**int**``)``**pow**``(2, x) - 1;`

`// Allocate memory`

`**int**``* st =` `**new**` `**int**``[max_size];`

`// Fill the allocated memory st`

`constructSTUtil(arr, 0, n - 1, st, 0);`

`// Return the constructed segment tree`

`**return**` `st;`

`}`

`// Driver code`

`**int**` `main()`

`{`

`**int**` `arr[] = { 1, 3, 5, 7, 9, 11 };`

`**int**` `n =` `**sizeof**``(arr) /` `**sizeof**``(arr);`

`**int**` `Q`

`= { { 1, 1, 3 },`

`{ 2, 1, 10 },`

`{ 1, 1, 3 } };`

`// Function call`

`SieveOfEratosthenes();`

`// Build segment tree from given array`

`**int**``* st = constructST(arr, n);`

`// Print sum of values in`

`// array from index 1 to 3`

`cout << getSum(st, n, 1, 3) << endl;`

`// Update: set arr = 10`

`// and update corresponding`

`// segment tree nodes`

`updateValue(arr, st, n, 1, 10);`

`// Find sum after the value is updated`

`cout << getSum(st, n, 1, 3) << endl;`

`**return**` `0;`

`}`

Output:

``````15
12
``````

Time Complexity:_ O(Q * log N) _

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#advanced data structure #arrays #dynamic programming #hash #mathematical #tree #array-range-queries #prime number #segment-tree #sieve

## Buddha Community  1596631020

## Sum of prime numbers in range [L, R] from given Array for Q queries

Given an array arr[] of the size of N followed by an array of Q queries, of the following two types:

• Query Type 1: Given two integers L and R, find the sum of prime elements from index L to R where 0 <= L <= R <= N-1.
• Query Type 2: Given two integers i and X, change arr[i] = X where 0 <= i <= n-1.

Note:_ Every first index of the subquery determines the type of query to be answered._

**Example: **

_Input: _arr[] = {1, 3, 5, 7, 9, 11}, Q = { { 1, 1, 3}, {2, 1, 10}, {1, 1, 3 } }

_Output: _

15

12

_Explanation: _

First query is of type 1, so answer is (3 + 5 + 7), = 15

Second query is of type 2, so arr = 10

Third query is of type 1, where arr = 10, which is not prime hence answer is (5 + 7) = 12

Input:_ arr[] = {1, 2, 35, 7, 14, 11}, Q = { {2, 4, 3}, {1, 4, 5 } }_

Output:_ 14_

Explanation:

First query is of type 2, So update arr = 3

Second query is of type 1, since arr = 3, which is prime. So answer is (3 + 11) = 14

**Naive Approach: **The idea is to iterate for each query between L to R and perform the required operation on the given array.

_Time Complexity: _O(Q * N * (O(sqrt(max(arr[i]))

**Approach: ** To optimize the problem use Segment tree and Sieve Of Eratosthenes.

• First, create a boolean array that will mark the prime numbers.
• Now while making the segment tree only add those array elements as leaf nodes which are prime.
• C++
• Python3

`// C++ program for the above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`**int**` `**const**` `MAX = 1000001;`

`**bool**` `prime[MAX];`

`// Function to find the prime numbers`

`**void**` `SieveOfEratosthenes()`

`{`

`// Create a boolean array prime[]`

`// and initialize all entries it as true`

`// A value in prime[i] will`

`// finally be false if i is Not a prime`

`**memset**``(prime,` `**true**``,` `**sizeof**``(prime));`

`**for**` `(``**int**` `p = 2; p * p <= MAX; p++) {`

`// Check if prime[p] is not`

`// changed, then it is a prime`

`**if**` `(prime[p] ==` `**true**``) {`

`// Update all multiples of p`

`// greater than or equal to`

`// the square of it numbers`

`// which are multiple of p`

`// and are less than p^2 are`

`// already been marked`

`**for**` `(``**int**` `i = p * p; i <= MAX; i += p)`

`prime[i] =` `**false**``;`

`}`

`}`

`}`

`// Function to get the middle`

`// index from corner indexes`

`**int**` `getMid(``**int**` `s,` `**int**` `e)`

`{`

`**return**` `s + (e - s) / 2;`

`}`

`// Function to get the sum of`

`// values in the given range`

`// of the array`

`**int**` `getSumUtil(``**int**``* st,` `**int**` `ss,`

`**int**` `se,` `**int**` `qs,`

`**int**` `qe,` `**int**` `si)`

`{`

`// If segment of this node is a`

`// part of given range, then`

`// return the sum of the segment`

`**if**` `(qs <= ss && qe >= se)`

`**return**` `st[si];`

`// If segment of this node is`

`// outside the given range`

`**if**` `(se < qs || ss > qe)`

`**return**` `0;`

`// If a part of this segment`

`// overlaps with the given range`

`**int**` `mid = getMid(ss, se);`

`**return**` `getSumUtil(st, ss, mid,`

`qs, qe,`

`2 * si + 1)`

`+ getSumUtil(st, mid + 1,`

`se, qs, qe,`

`2 * si + 2);`

`}`

`// Function to update the nodes which`

`// have the given index in their range`

`**void**` `updateValueUtil(``**int**``* st,` `**int**` `ss,`

`**int**` `se,` `**int**` `i,`

`**int**` `diff,` `**int**` `si)`

`{`

`// If the input index lies`

`// outside the range of`

`// this segment`

`**if**` `(i < ss || i > se)`

`**return**``;`

`// If the input index is in`

`// range of this node, then update`

`// the value of the node and its children`

`st[si] = st[si] + diff;`

`**if**` `(se != ss) {`

`**int**` `mid = getMid(ss, se);`

`updateValueUtil(st, ss, mid, i,`

`diff, 2 * si + 1);`

`updateValueUtil(st, mid + 1,`

`se, i, diff,`

`2 * si + 2);`

`}`

`}`

`// Function to update a value in`

`// input array and segment tree`

`**void**` `updateValue(``**int**` `arr[],` `**int**``* st,`

`**int**` `n,` `**int**` `i,`

`**int**` `new_val)`

`{`

`// Check for erroneous input index`

`**if**` `(i < 0 || i > n - 1) {`

`cout <<` `"-1"``;`

`**return**``;`

`}`

`// Get the difference between`

`// new value and old value`

`**int**` `diff = new_val - arr[i];`

`**int**` `prev_val = arr[i];`

`// Update the value in array`

`arr[i] = new_val;`

`// Update the values of`

`// nodes in segment tree`

`// only if either previous`

`// value or new value`

`// or both are prime`

`**if**` `(prime[new_val]`

`|| prime[prev_val]) {`

`// If only new value is prime`

`**if**` `(!prime[prev_val])`

`updateValueUtil(st, 0, n - 1,`

`i, new_val, 0);`

`// If only new value is prime`

`**else**` `**if**` `(!prime[new_val])`

`updateValueUtil(st, 0, n - 1,`

`i, -prev_val, 0);`

`// If both are prime`

`**else**`

`updateValueUtil(st, 0, n - 1,`

`i, diff, 0);`

`}`

`}`

`// Return sum of elements in range`

`// from index qs (quey start) to qe`

`// (query end). It mainly uses getSumUtil()`

`**int**` `getSum(``**int**``* st,` `**int**` `n,` `**int**` `qs,` `**int**` `qe)`

`{`

`// Check for erroneous input values`

`**if**` `(qs < 0 || qe > n - 1 || qs > qe) {`

`cout <<` `"-1"``;`

`**return**` `-1;`

`}`

`**return**` `getSumUtil(st, 0, n - 1,`

`qs, qe, 0);`

`}`

`// Function that constructs Segment Tree`

`**int**` `constructSTUtil(``**int**` `arr[],` `**int**` `ss,`

`**int**` `se,` `**int**``* st,`

`**int**` `si)`

`{`

`// If there is one element in`

`// array, store it in current node of`

`// segment tree and return`

`**if**` `(ss == se) {`

`// Only add those elements in segment`

`// tree which are prime`

`**if**` `(prime[arr[ss]])`

`st[si] = arr[ss];`

`**else**`

`st[si] = 0;`

`**return**` `st[si];`

`}`

`// If there are more than one`

`// elements, then recur for left and`

`// right subtrees and store the`

`// sum of values in this node`

`**int**` `mid = getMid(ss, se);`

`st[si]`

`= constructSTUtil(arr, ss, mid,`

`st, si * 2 + 1)`

`+ constructSTUtil(arr, mid + 1,`

`se, st,`

`si * 2 + 2);`

`**return**` `st[si];`

`}`

`// Function to construct segment`

`// tree from given array`

`**int**``* constructST(``**int**` `arr[],` `**int**` `n)`

`{`

`// Allocate memory for the segment tree`

`// Height of segment tree`

`**int**` `x = (``**int**``)(``**ceil**``(log2(n)));`

`// Maximum size of segment tree`

`**int**` `max_size = 2 * (``**int**``)``**pow**``(2, x) - 1;`

`// Allocate memory`

`**int**``* st =` `**new**` `**int**``[max_size];`

`// Fill the allocated memory st`

`constructSTUtil(arr, 0, n - 1, st, 0);`

`// Return the constructed segment tree`

`**return**` `st;`

`}`

`// Driver code`

`**int**` `main()`

`{`

`**int**` `arr[] = { 1, 3, 5, 7, 9, 11 };`

`**int**` `n =` `**sizeof**``(arr) /` `**sizeof**``(arr);`

`**int**` `Q`

`= { { 1, 1, 3 },`

`{ 2, 1, 10 },`

`{ 1, 1, 3 } };`

`// Function call`

`SieveOfEratosthenes();`

`// Build segment tree from given array`

`**int**``* st = constructST(arr, n);`

`// Print sum of values in`

`// array from index 1 to 3`

`cout << getSum(st, n, 1, 3) << endl;`

`// Update: set arr = 10`

`// and update corresponding`

`// segment tree nodes`

`updateValue(arr, st, n, 1, 10);`

`// Find sum after the value is updated`

`cout << getSum(st, n, 1, 3) << endl;`

`**return**` `0;`

`}`

Output:

``````15
12
``````

Time Complexity:_ O(Q * log N) _

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#advanced data structure #arrays #dynamic programming #hash #mathematical #tree #array-range-queries #prime number #segment-tree #sieve 1649209980

## C# REPL

A cross-platform command line REPL for the rapid experimentation and exploration of C#. It supports intellisense, installing NuGet packages, and referencing local .NET projects and assemblies. (click to view animation)

C# REPL provides the following features:

• Syntax highlighting via ANSI escape sequences
• Intellisense with fly-out documentation
• Nuget package installation
• Reference local assemblies, solutions, and projects
• Navigate to source via Source Link
• IL disassembly (both Debug and Release mode)
• Fast and flicker-free rendering. A "diff" algorithm is used to only render what's changed.

## Installation

C# REPL is a .NET 6 global tool, and runs on Windows 10, Mac OS, and Linux. It can be installed via:

``````dotnet tool install -g csharprepl
``````

If you're running on Mac OS Catalina (10.15) or later, make sure you follow any additional directions printed to the screen. You may need to update your PATH variable in order to use .NET global tools.

After installation is complete, run `csharprepl` to begin. C# REPL can be updated via `dotnet tool update -g csharprepl`.

## Usage:

Run `csharprepl` from the command line to begin an interactive session. The default colorscheme uses the color palette defined by your terminal, but these colors can be changed using a `theme.json` file provided as a command line argument.

### Evaluating Code

Type some C# into the prompt and press Enter to run it. The result, if any, will be printed:

``````> Console.WriteLine("Hello World")
Hello World

[6/7/2021 5:13:00 PM]
``````

To evaluate multiple lines of code, use Shift+Enter to insert a newline:

``````> var x = 5;
var y = 8;
x * y
40
``````

Additionally, if the statement is not a "complete statement" a newline will automatically be inserted when Enter is pressed. For example, in the below code, the first line is not a syntactically complete statement, so when we press enter we'll go down to a new line:

``````> if (x == 5)
| // caret position, after we press Enter on Line 1
``````

Finally, pressing Ctrl+Enter will show a "detailed view" of the result. For example, for the `DateTime.Now` expression below, on the first line we pressed Enter, and on the second line we pressed Ctrl+Enter to view more detailed output:

``````> DateTime.Now // Pressing Enter shows a reasonable representation
[5/30/2021 5:13:00 PM]

> DateTime.Now // Pressing Ctrl+Enter shows a detailed representation
[5/30/2021 5:13:00 PM] {
Date: [5/30/2021 12:00:00 AM],
Day: 30,
DayOfWeek: Sunday,
DayOfYear: 150,
Hour: 17,
InternalKind: 9223372036854775808,
InternalTicks: 637579915804530992,
Kind: Local,
Millisecond: 453,
Minute: 13,
Month: 5,
Second: 0,
Ticks: 637579915804530992,
TimeOfDay: [17:13:00.4530992],
Year: 2021,
_dateData: 9860951952659306800
}
``````

A note on semicolons: C# expressions do not require semicolons, but statements do. If a statement is missing a required semicolon, a newline will be added instead of trying to run the syntatically incomplete statement; simply type the semicolon to complete the statement.

``````> var now = DateTime.Now; // assignment statement, semicolon required

> DateTime.Now.AddDays(8) // expression, we don't need a semicolon
[6/7/2021 5:03:05 PM]
``````

### Keyboard Shortcuts

• Basic Usage
• Ctrl+C - Cancel current line
• Ctrl+L - Clear screen
• Enter - Evaluate the current line if it's a syntactically complete statement; otherwise add a newline
• Control+Enter - Evaluate the current line, and return a more detailed representation of the result
• Shift+Enter - Insert a new line (this does not currently work on Linux or Mac OS; Hopefully this will work in .NET 7)
• Ctrl+Shift+C - Copy current line to clipboard
• Ctrl+V, Shift+Insert, and Ctrl+Shift+V - Paste text to prompt. Automatically trims leading indent
• Code Actions
• F1 - Opens the MSDN documentation for the class/method under the caret (example)
• F9 - Shows the IL (intermediate language) for the current statement in Debug mode.
• Ctrl+F9 - Shows the IL for the current statement with Release mode optimizations.
• F12 - Opens the source code in the browser for the class/method under the caret, if the assembly supports Source Link.
• Autocompletion
• Ctrl+Space - Open autocomplete menu. If there's a single option, pressing Ctrl+Space again will select the option
• Enter, Right Arrow, Tab - Select active autocompletion option
• Escape - closes autocomplete menu
• Home and End - Navigate to beginning of a single line and end of a single line, respectively
• Ctrl+Home and Ctrl+End - Navigate to beginning of line and end across multiple lines in a multiline prompt, respectively
• Arrows - Navigate characters within text
• Ctrl+Arrows - Navigate words within text
• Ctrl+Backspace - Delete previous word
• Ctrl+Delete - Delete next word

Use the `#r` command to add assembly or nuget references.

• For assembly references, run `#r "AssemblyName"` or `#r "path/to/assembly.dll"`
• For project references, run `#r "path/to/project.csproj"`. Solution files (.sln) can also be referenced.
• For nuget references, run `#r "nuget: PackageName"` to install the latest version of a package, or `#r "nuget: PackageName, 13.0.5"` to install a specific version (13.0.5 in this case). To run ASP.NET applications inside the REPL, start the `csharprepl `application with the `--framework` parameter, specifying the `Microsoft.AspNetCore.App` shared framework. Then, use the above `#r` command to reference the application DLL. See the Command Line Configuration section below for more details.

``````csharprepl --framework  Microsoft.AspNetCore.App
``````

## Command Line Configuration

The C# REPL supports multiple configuration flags to control startup, behavior, and appearance:

``````csharprepl [OPTIONS] [response-file.rsp] [script-file.csx] [-- <additional-arguments>]
``````

Supported options are:

• OPTIONS:
• `-r <dll>` or `--reference <dll>`: Reference an assembly, project file, or nuget package. Can be specified multiple times. Uses the same syntax as `#r` statements inside the REPL. For example, `csharprepl -r "nuget:Newtonsoft.Json" "path/to/myproj.csproj"`
• When an assembly or project is referenced, assemblies in the containing directory will be added to the assembly search path. This means that you don't need to manually add references to all of your assembly's dependencies (e.g. other references and nuget packages). Referencing the main entry assembly is enough.
• `-u <namespace>` or `--using <namespace>`: Add a using statement. Can be specified multiple times.
• `-f <framework>` or `--framework <framework>`: Reference a shared framework. The available shared frameworks depends on the local .NET installation, and can be useful when running an ASP.NET application from the REPL. Example frameworks are:
• Microsoft.NETCore.App (default)
• Microsoft.AspNetCore.All
• Microsoft.AspNetCore.App
• Microsoft.WindowsDesktop.App
• `-t <theme.json>` or `--theme <theme.json>`: Read a theme file for syntax highlighting. This theme file associates C# syntax classifications with colors. The color values can be full RGB, or ANSI color names (defined in your terminal's theme). The NO_COLOR standard is supported.
• `--trace`: Produce a trace file in the current directory that logs CSharpRepl internals. Useful for CSharpRepl bug reports.
• `-v` or `--version`: Show version number and exit.
• `-h` or `--help`: Show help and exit.
• `response-file.rsp`: A filepath of an .rsp file, containing any of the above command line options.
• `script-file.csx`: A filepath of a .csx file, containing lines of C# to evaluate before starting the REPL. Arguments to this script can be passed as `<additional-arguments>`, after a double hyphen (`--`), and will be available in a global `args` variable.

If you have `dotnet-suggest` enabled, all options can be tab-completed, including values provided to `--framework` and .NET namespaces provided to `--using`.

## Integrating with other software

C# REPL is a standalone software application, but it can be useful to integrate it with other developer tools:

### Windows Terminal

To add C# REPL as a menu entry in Windows Terminal, add the following profile to Windows Terminal's `settings.json` configuration file (under the JSON property `profiles.list`):

``````{
"name": "C# REPL",
"commandline": "csharprepl"
},
``````

To get the exact colors shown in the screenshots in this README, install the Windows Terminal Dracula theme.

### Visual Studio Code

To use the C# REPL with Visual Studio Code, simply run the `csharprepl` command in the Visual Studio Code terminal. To send commands to the REPL, use the built-in `Terminal: Run Selected Text In Active Terminal` command from the Command Palette (`workbench.action.terminal.runSelectedText`). ### Windows OS

To add the C# REPL to the Windows Start Menu for quick access, you can run the following PowerShell command, which will start C# REPL in Windows Terminal:

``````\$shell = New-Object -ComObject WScript.Shell
\$shortcut.TargetPath = "wt.exe"
\$shortcut.Arguments = "-w 0 nt csharprepl.exe"
\$shortcut.Save()
``````

You may also wish to add a shorter alias for C# REPL, which can be done by creating a `.cmd` file somewhere on your path. For example, put the following contents in `C:\Users\username\.dotnet\tools\csr.cmd`:

``````wt -w 0 nt csharprepl
``````

This will allow you to launch C# REPL by running `csr` from anywhere that accepts Windows commands, like the Window Run dialog.

## Comparison with other REPLs

This project is far from being the first REPL for C#. Here are some other projects; if this project doesn't suit you, another one might!

Visual Studio's C# Interactive pane is full-featured (it has syntax highlighting and intellisense) and is part of Visual Studio. This deep integration with Visual Studio is both a benefit from a workflow perspective, and a drawback as it's not cross-platform. As far as I know, the C# Interactive pane does not support NuGet packages or navigating to documentation/source code. Subjectively, it does not follow typical command line keybindings, so can feel a bit foreign.

csi.exe ships with C# and is a command line REPL. It's great because it's a cross platform REPL that comes out of the box, but it doesn't support syntax highlighting or autocompletion.

dotnet script allows you to run C# scripts from the command line. It has a REPL built-in, but the predominant focus seems to be as a script runner. It's a great tool, though, and has a strong community following.

dotnet interactive is a tool from Microsoft that creates a Jupyter notebook for C#, runnable through Visual Studio Code. It also provides a general framework useful for running REPLs.

Author: waf
Source Code: https://github.com/waf/CSharpRepl 1647064260

## dotnet script

Run C# scripts from the .NET CLI, define NuGet packages inline and edit/debug them in VS Code - all of that with full language services support from OmniSharp.

## Installing

### Prerequisites

The only thing we need to install is .NET Core 3.1 or .NET 5.0 SDK.

### .NET Core Global Tool

.NET Core 2.1 introduced the concept of global tools meaning that you can install `dotnet-script` using nothing but the .NET CLI.

``````dotnet tool install -g dotnet-script

You can invoke the tool using the following command: dotnet-script
Tool 'dotnet-script' (version '0.22.0') was successfully installed.
``````

The advantage of this approach is that you can use the same command for installation across all platforms. .NET Core SDK also supports viewing a list of installed tools and their uninstallation.

``````dotnet tool list -g

Package Id         Version      Commands
---------------------------------------------
dotnet-script      0.22.0       dotnet-script
``````
``````dotnet tool uninstall dotnet-script -g

Tool 'dotnet-script' (version '0.22.0') was successfully uninstalled.
``````

### Windows

``````choco install dotnet.script
``````

We also provide a PowerShell script for installation.

``````(new-object Net.WebClient).DownloadString("https://raw.githubusercontent.com/filipw/dotnet-script/master/install/install.ps1") | iex
``````

### Linux and Mac

``````curl -s https://raw.githubusercontent.com/filipw/dotnet-script/master/install/install.sh | bash
``````

If permission is denied we can try with `sudo`

``````curl -s https://raw.githubusercontent.com/filipw/dotnet-script/master/install/install.sh | sudo bash
``````

### Docker

A Dockerfile for running dotnet-script in a Linux container is available. Build:

``````cd build
docker build -t dotnet-script -f Dockerfile ..
``````

And run:

``````docker run -it dotnet-script --version
``````

### Github

You can manually download all the releases in `zip` format from the GitHub releases page.

## Usage

Our typical `helloworld.csx` might look like this:

``````Console.WriteLine("Hello world!");
``````

That is all it takes and we can execute the script. Args are accessible via the global Args array.

``````dotnet script helloworld.csx
``````

### Scaffolding

Simply create a folder somewhere on your system and issue the following command.

``````dotnet script init
``````

This will create `main.csx` along with the launch configuration needed to debug the script in VS Code.

``````.
├── .vscode
│   └── launch.json
├── main.csx
└── omnisharp.json
``````

We can also initialize a folder using a custom filename.

``````dotnet script init custom.csx
``````

Instead of `main.csx` which is the default, we now have a file named `custom.csx`.

``````.
├── .vscode
│   └── launch.json
├── custom.csx
└── omnisharp.json
``````

Note: Executing `dotnet script init` inside a folder that already contains one or more script files will not create the `main.csx` file.

### Running scripts

Scripts can be executed directly from the shell as if they were executables.

``````foo.csx arg1 arg2 arg3
``````

OSX/Linux

Just like all scripts, on OSX/Linux you need to have a `#!` and mark the file as executable via chmod +x foo.csx. If you use dotnet script init to create your csx it will automatically have the `#!` directive and be marked as executable.

The OSX/Linux shebang directive should be #!/usr/bin/env dotnet-script

``````#!/usr/bin/env dotnet-script
Console.WriteLine("Hello world");
``````

You can execute your script using dotnet script or dotnet-script, which allows you to pass arguments to control your script execution more.

``````foo.csx arg1 arg2 arg3
dotnet script foo.csx -- arg1 arg2 arg3
dotnet-script foo.csx -- arg1 arg2 arg3
``````

#### Passing arguments to scripts

All arguments after `--` are passed to the script in the following way:

``````dotnet script foo.csx -- arg1 arg2 arg3
``````

Then you can access the arguments in the script context using the global `Args` collection:

``````foreach (var arg in Args)
{
Console.WriteLine(arg);
}
``````

All arguments before `--` are processed by `dotnet script`. For example, the following command-line

``````dotnet script -d foo.csx -- -d
``````

will pass the `-d` before `--` to `dotnet script` and enable the debug mode whereas the `-d` after `--` is passed to script for its own interpretation of the argument.

### NuGet Packages

`dotnet script` has built-in support for referencing NuGet packages directly from within the script.

``````#r "nuget: AutoMapper, 6.1.0"
`````` Note: Omnisharp needs to be restarted after adding a new package reference

#### Package Sources

We can define package sources using a `NuGet.Config` file in the script root folder. In addition to being used during execution of the script, it will also be used by `OmniSharp` that provides language services for packages resolved from these package sources.

As an alternative to maintaining a local `NuGet.Config` file we can define these package sources globally either at the user level or at the computer level as described in Configuring NuGet Behaviour

It is also possible to specify packages sources when executing the script.

``````dotnet script foo.csx -s https://SomePackageSource
``````

Multiple packages sources can be specified like this:

``````dotnet script foo.csx -s https://SomePackageSource -s https://AnotherPackageSource
``````

### Creating DLLs or Exes from a CSX file

Dotnet-Script can create a standalone executable or DLL for your script.

The executable you can run directly independent of dotnet install, while the DLL can be run using the dotnet CLI like this:

``````dotnet script exec {path_to_dll} -- arg1 arg2
``````

### Caching

We provide two types of caching, the `dependency cache` and the `execution cache` which is explained in detail below. In order for any of these caches to be enabled, it is required that all NuGet package references are specified using an exact version number. The reason for this constraint is that we need to make sure that we don't execute a script with a stale dependency graph.

#### Dependency Cache

In order to resolve the dependencies for a script, a `dotnet restore` is executed under the hood to produce a `project.assets.json` file from which we can figure out all the dependencies we need to add to the compilation. This is an out-of-process operation and represents a significant overhead to the script execution. So this cache works by looking at all the dependencies specified in the script(s) either in the form of NuGet package references or assembly file references. If these dependencies matches the dependencies from the last script execution, we skip the restore and read the dependencies from the already generated `project.assets.json` file. If any of the dependencies has changed, we must restore again to obtain the new dependency graph.

#### Execution cache

In order to execute a script it needs to be compiled first and since that is a CPU and time consuming operation, we make sure that we only compile when the source code has changed. This works by creating a SHA256 hash from all the script files involved in the execution. This hash is written to a temporary location along with the DLL that represents the result of the script compilation. When a script is executed the hash is computed and compared with the hash from the previous compilation. If they match there is no need to recompile and we run from the already compiled DLL. If the hashes don't match, the cache is invalidated and we recompile.

You can override this automatic caching by passing --no-cache flag, which will bypass both caches and cause dependency resolution and script compilation to happen every time we execute the script.

#### Cache Location

The temporary location used for caches is a sub-directory named `dotnet-script` under (in order of priority):

1. The path specified for the value of the environment variable named `DOTNET_SCRIPT_CACHE_LOCATION`, if defined and value is not empty.
2. Linux distributions only: `\$XDG_CACHE_HOME` if defined otherwise `\$HOME/.cache`
3. macOS only: `~/Library/Caches`
4. The value returned by `Path.GetTempPath` for the platform.

### Debugging

The days of debugging scripts using `Console.WriteLine` are over. One major feature of `dotnet script` is the ability to debug scripts directly in VS Code. Just set a breakpoint anywhere in your script file(s) and hit F5(start debugging) ### Script Packages

Script packages are a way of organizing reusable scripts into NuGet packages that can be consumed by other scripts. This means that we now can leverage scripting infrastructure without the need for any kind of bootstrapping.

#### Creating a script package

A script package is just a regular NuGet package that contains script files inside the `content` or `contentFiles` folder.

The following example shows how the scripts are laid out inside the NuGet package according to the standard convention .

``````└── contentFiles
└── csx
└── netstandard2.0
└── main.csx
``````

This example contains just the `main.csx` file in the root folder, but packages may have multiple script files either in the root folder or in subfolders below the root folder.

When loading a script package we will look for an entry point script to be loaded. This entry point script is identified by one of the following.

• A script called `main.csx` in the root folder
• A single script file in the root folder

If the entry point script cannot be determined, we will simply load all the scripts files in the package.

The advantage with using an entry point script is that we can control loading other scripts from the package.

#### Consuming a script package

To consume a script package all we need to do specify the NuGet package in the `#load`directive.

The following example loads the simple-targets package that contains script files to be included in our script.

``````#load "nuget:simple-targets-csx, 6.0.0"

using static SimpleTargets;
var targets = new TargetDictionary();

Run(Args, targets);
``````

Note: Debugging also works for script packages so that we can easily step into the scripts that are brought in using the `#load` directive.

### Remote Scripts

Scripts don't actually have to exist locally on the machine. We can also execute scripts that are made available on an `http(s)` endpoint.

This means that we can create a Gist on Github and execute it just by providing the URL to the Gist.

This Gist contains a script that prints out "Hello World"

We can execute the script like this

``````dotnet script https://gist.githubusercontent.com/seesharper/5d6859509ea8364a1fdf66bbf5b7923d/raw/0a32bac2c3ea807f9379a38e251d93e39c8131cb/HelloWorld.csx
``````

That is a pretty long URL, so why don't make it a TinyURL like this:

``````dotnet script https://tinyurl.com/y8cda9zt
``````

### Script Location

A pretty common scenario is that we have logic that is relative to the script path. We don't want to require the user to be in a certain directory for these paths to resolve correctly so here is how to provide the script path and the script folder regardless of the current working directory.

``````public static string GetScriptPath([CallerFilePath] string path = null) => path;
public static string GetScriptFolder([CallerFilePath] string path = null) => Path.GetDirectoryName(path);
``````

Tip: Put these methods as top level methods in a separate script file and `#load` that file wherever access to the script path and/or folder is needed.

## REPL

This release contains a C# REPL (Read-Evaluate-Print-Loop). The REPL mode ("interactive mode") is started by executing `dotnet-script` without any arguments.

The interactive mode allows you to supply individual C# code blocks and have them executed as soon as you press Enter. The REPL is configured with the same default set of assembly references and using statements as regular CSX script execution.

### Basic usage

Once `dotnet-script` starts you will see a prompt for input. You can start typing C# code there.

``````~\$ dotnet script
> var x = 1;
> x+x
2
``````

If you submit an unterminated expression into the REPL (no `;` at the end), it will be evaluated and the result will be serialized using a formatter and printed in the output. This is a bit more interesting than just calling `ToString()` on the object, because it attempts to capture the actual structure of the object. For example:

``````~\$ dotnet script
> var x = new List<string>();
> x
List<string>(1) { "foo" }
> x
List<string>(2) { "foo", "bar" }
>
``````

### Inline Nuget packages

REPL also supports inline Nuget packages - meaning the Nuget packages can be installed into the REPL from within the REPL. This is done via our `#r` and `#load` from Nuget support and uses identical syntax.

``````~\$ dotnet script
> #r "nuget: Automapper, 6.1.1"
> using AutoMapper;
> typeof(MapperConfiguration)
[AutoMapper.MapperConfiguration]
> using static SimpleTargets;
> typeof(TargetDictionary)
[Submission#0+SimpleTargets+TargetDictionary]
``````

### Multiline mode

Using Roslyn syntax parsing, we also support multiline REPL mode. This means that if you have an uncompleted code block and press Enter, we will automatically enter the multiline mode. The mode is indicated by the `*` character. This is particularly useful for declaring classes and other more complex constructs.

``````~\$ dotnet script
> class Foo {
* public string Bar {get; set;}
* }
> var foo = new Foo();
``````

### REPL commands

Aside from the regular C# script code, you can invoke the following commands (directives) from within the REPL:

### Seeding REPL with a script

You can execute a CSX script and, at the end of it, drop yourself into the context of the REPL. This way, the REPL becomes "seeded" with your code - all the classes, methods or variables are available in the REPL context. This is achieved by running a script with an `-i` flag.

For example, given the following CSX script:

``````var msg = "Hello World";
Console.WriteLine(msg);
``````

When you run this with the `-i` flag, `Hello World` is printed, REPL starts and `msg` variable is available in the REPL context.

``````~\$ dotnet script foo.csx -i
Hello World
>
``````

You can also seed the REPL from inside the REPL - at any point - by invoking a `#load` directive pointed at a specific file. For example:

``````~\$ dotnet script
Hello World
>
``````

## Piping

The following example shows how we can pipe data in and out of a script.

The `UpperCase.csx` script simply converts the standard input to upper case and writes it back out to standard output.

``````using (var streamReader = new StreamReader(Console.OpenStandardInput()))
{
}
``````

We can now simply pipe the output from one command into our script like this.

``````echo "This is some text" | dotnet script UpperCase.csx
THIS IS SOME TEXT
``````

### Debugging

The first thing we need to do add the following to the `launch.config` file that allows VS Code to debug a running process.

``````{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "\${command:pickProcess}"
}
``````

To debug this script we need a way to attach the debugger in VS Code and the simplest thing we can do here is to wait for the debugger to attach by adding this method somewhere.

``````public static void WaitForDebugger()
{
Console.WriteLine("Attach Debugger (VS Code)");
while(!Debugger.IsAttached)
{
}
}
``````

To debug the script when executing it from the command line we can do something like

``````WaitForDebugger();
{
}
``````

Now when we run the script from the command line we will get

``````\$ echo "This is some text" | dotnet script UpperCase.csx
Attach Debugger (VS Code)
``````

This now gives us a chance to attach the debugger before stepping into the script and from VS Code, select the `.NET Core Attach` debugger and pick the process that represents the executing script.

Once that is done we should see our breakpoint being hit.

## Configuration(Debug/Release)

By default, scripts will be compiled using the `debug` configuration. This is to ensure that we can debug a script in VS Code as well as attaching a debugger for long running scripts.

There are however situations where we might need to execute a script that is compiled with the `release` configuration. For instance, running benchmarks using BenchmarkDotNet is not possible unless the script is compiled with the `release` configuration.

We can specify this when executing the script.

``````dotnet script foo.csx -c release
``````

## Nullable reference types

Starting from version 0.50.0, `dotnet-script` supports .Net Core 3.0 and all the C# 8 features. The way we deal with nullable references types in `dotnet-script` is that we turn every warning related to nullable reference types into compiler errors. This means every warning between `CS8600` and `CS8655` are treated as an error when compiling the script.

Nullable references types are turned off by default and the way we enable it is using the `#nullable enable` compiler directive. This means that existing scripts will continue to work, but we can now opt-in on this new feature.

``````#!/usr/bin/env dotnet-script

#nullable enable

string name = null;
``````

Trying to execute the script will result in the following error

``````main.csx(5,15): error CS8625: Cannot convert null literal to non-nullable reference type.
``````

We will also see this when working with scripts in VS Code under the problems panel. Author: filipw
Source Code: https://github.com/filipw/dotnet-script 1596962520

## Queries to find the Lower Bound of K from Prefix Sum Array

Given an array A[ ] consisting of non-negative integers and matrix Q[ ][ ] consisting of queries of the following two types:

• **(1, l, val): **Update A[l] to A[l] + val.
• **(2, K): **Find the lower_bound of **K **in the prefix sum array of A[ ]. If the lower_bound does not exist print -1.

The task for each query of second type is to print the index of lower_bound of value K.

Examples:

_Input: __A[ ] = {1, 2, 3, 5, 8}, Q[ ][ ] = {{1, 0, 2}, {2, 5}, {1, 3, 5}} _

_Output: __1 _

Explanation:

Query 1: Update A to A + 2. Now A[ ] = {3, 2, 3, 5, 8}

_Query 2: lower_bound of K = 5 in the prefix sum array {3, 5, 8, 13, 21} is 5 and index = 1. _

Query 3: Update A to A + 5. Now A[ ] = {3, 2, 3, 10, 8}

_Input: __A[ ] = {4, 1, 12, 8, 20}, Q[ ] = {{2, 50}, {1, 3, 12}, {2, 50}} _

_Output: __-1 _

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive approach:

The simplest approach is to firstly build a prefix sum array of given array A[ ], and for queries of Type 1, update values and recalculate the prefix sum. For query of Type 2, perform a Binary Search on the prefix sum array to find lower bound.

Time Complexity:_ O(Q*(N*logn))_

_Auxiliary Space: _O(N)

Efficient Approach:

The above approach can be optimized using Fenwick Tree. Using this Data Structure, the update queries in prefix sum array can be performed in logarithmic time.

Follow the steps below to solve the problem:

• Construct the Prefix Sum Array using Fenwick Tree.
• For queries of Type 1, while** l > 0**, add val to A[l] traverse to the parent node by adding least significant bit in l.
• For queries of Type 2, perform the Binary Search on the Fenwick Tree to obtain the lower bound.
• Whenever a prefix sum greater than **K appears, **store that **index **and traverse the left part of the Fenwick Tree. Otherwise, traverse the right part of the Fenwick Tree Now, perform Binary Search.
• Finally, print the required index.

Below is the implementation of the above approach:

• Java
• C#

`// Java program to implement`

`// the above appraoch`

`**import**` `java.util.*;`

`**import**` `java.io.*;`

`**class**` `GFG {`

`// Function to calculate and return`

`// the sum of arr[0..index]`

`**static**` `**int**` `getSum(``**int**` `BITree[],`

`**int**` `index)`

`{`

`**int**` `ans =` `0``;`

`index +=` `1``;`

`// Traverse ancestors`

`// of BITree[index]`

`**while**` `(index >` `0``) {`

`// Update the sum of current`

`// element of BIT to ans`

`ans += BITree[index];`

`// Update index to that`

`// of the parent node in`

`// getSum() view by`

`// subtracting LSB(Least`

`// Significant Bit)`

`index -= index & (-index);`

`}`

`**return**` `ans;`

`}`

`// Function to update the Binary Index`

`// Tree by replacing all ancestores of`

`// index by their respective sum with val`

`**static**` `**void**` `updateBIT(``**int**` `BITree[],`

`**int**` `n,` `**int**` `index,` `**int**` `val)`

`{`

`index = index +` `1``;`

`// Traverse all ancestors`

`// and sum with 'val'.`

`**while**` `(index <= n) {`

`// Add 'val' to current`

`// node of BIT`

`BITree[index] += val;`

`// Update index to that`

`// of the parent node in`

`// updateBit() view by`

`// adding LSB(Least`

`// Significant Bit)`

`index += index & (-index);`

`}`

`}`

`// Function to construct the Binary`

`// Indexed Tree for the given array`

`**static**` `**int**``[] constructBITree(`

`**int**` `arr[],` `**int**` `n)`

`{`

`// Initialize the`

`// Binary Indexed Tree`

`**int**``[] BITree =` `**new**` `**int**``[n +` `1``];`

`**for**` `(``**int**` `i =` `0``; i <= n; i++)`

`BITree[i] =` `0``;`

`// Store the actual values in`

`// BITree[] using update()`

`**for**` `(``**int**` `i =` `0``; i < n; i++)`

`updateBIT(BITree, n, i, arr[i]);`

`**return**` `BITree;`

`}`

`// Function to obtian and return`

`// the index of lower_bound of k`

`**static**` `**int**` `getLowerBound(``**int**` `BITree[],`

`**int**``[] arr,` `**int**` `n,` `**int**` `k)`

`{`

`**int**` `lb = -``1``;`

`**int**` `l =` `0``, r = n -` `1``;`

`**while**` `(l <= r) {`

`**int**` `mid = l + (r - l) /` `2``;`

`**if**` `(getSum(BITree, mid) >= k) {`

`r = mid -` `1``;`

`lb = mid;`

`}`

`**else**`

`l = mid +` `1``;`

`}`

`**return**` `lb;`

`}`

`**static**` `**void**` `performQueries(``**int**` `A[],` `**int**` `n,` `**int**` `q[][])`

`{`

`// Store the Binary Indexed Tree`

`**int**``[] BITree = constructBITree(A, n);`

`// Solve each query in Q`

`**for**` `(``**int**` `i =` `0``; i < q.length; i++) {`

`**int**` `id = q[i][``0``];`

`**if**` `(id ==` `1``) {`

`**int**` `idx = q[i][``1``];`

`**int**` `val = q[i][``2``];`

`A[idx] += val;`

`// Update the values of all`

`// ancestors of idx`

`updateBIT(BITree, n, idx, val);`

`}`

`**else**` `{`

`**int**` `k = q[i][``1``];`

`**int**` `lb = getLowerBound(`

`BITree, A, n, k);`

`System.out.println(lb);`

`}`

`}`

`}`

`// Driver Code`

`**public**` `**static**` `**void**` `main(String[] args)`

`{`

`**int**` `A[] = {` `1``,` `2``,` `3``,` `5``,` `8` `};`

`**int**` `n = A.length;`

`**int**``[][] q = { {` `1``,` `0``,` `2` `},`

`{` `2``,` `5` `},`

`{` `1``,` `3``,` `5` `} };`

`performQueries(A, n, q);`

`}`

`}`

Output:

``````1
``````

Time Complexity:_ O(Q*(logN)2)_

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#advanced data structure #arrays #bit magic #mathematical #searching #array-range-queries #bit #prefix-sum 1593370497

## Sum and Maximum of elements in array from [L, R] updates

Prerequisite: Segment TreesLazy Propagation in Segment Tree.

Given an array arr[] of N integers. The task is to do the following operations:

1. Change the value arr[i] to min(arr[i], X) where X is an integer for a given range [L, R].
2. Find the maximum value from index L to R where 0 ≤ L ≤ R ≤ N-1 before and after the update given to the array above.
3. Find the sum of the element from index L to R where 0 ≤ L ≤ R ≤ N-1 before and after the update given to the array above.

Examples:

``````Input: arr[] = {1, 2, 3, 4, 5}, L = 2, R = 4, X = 3
Output:
Maximum in range [2, 4] before update: 5
Sum in range [2, 4] before update: 12
Maximum in range [2, 4] after update: 3
Sum in range [2, 4] after update: 9
Explanation:
Before Update:
arr[] = {1, 2, 3, 4, 5}
The maximum value from [L, R] is 5
Sum in range [L, R] is 3 + 4 + 5 = 12
After Update:
arr[] = {1, 2, 3, 3, 3}
The maximum value from [L, R] is 3
Sum in range [L, R] is 3 + 3 + 3 = 9
Input: arr[] = {1, 4, 19, 0, 7, 22, 7}, L = 1, R = 5, X = 14
Output:
Maximum in range [1, 5] before update: 22
Sum in range [1, 5] before update: 52
Maximum in range [1, 5] after update: 22
Sum in range [1, 5] after update: 39
Explanation:
Before Update:
arr[] = {1, 4, 19, 0, 7, 22, 7}
The maximum value from [L, R] is 22
Sum in range [L, R] is 4 + 19 + 0 + 7 + 22 = 52

After Update:
arr[] = {1, 4, 14, 0, 7, 14, 7}
The maximum value from [L, R] is 14
Sum in range [L, R] is 4 + 14 + 0 + 7 + 14 = 39
``````

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach:

1. pushdown(): The lazy tag is applied to current node and then is pushed down to its children.
2. tag_condition: It is the condition that needs to be satisfied to set the lazy node. In normal lazy trees, it is generally the condition that ranges of the node covers lie entirely in the update range.
3. A node in the segment tree represents a range of the array. Now all elements in that range will have different values and they will change by different amounts during an update. So we need the information about distinct values and their counts in that range. So this becomes a worst-case O**(N)** operation as at max N distinct nodes in a range.
4. Below is the approach to solve these restrictions in Segment Tree. Each node in the Segment Tree will have the following values:
• value: The value of a range, here sum of all elements in that range
• maxval: Maximum value in that range
• secondmax: Strict second maximum value in that range
• cnt_max: Count of maximum value in that range
• cnt_secondmax: Count of secondmax in that range

#advanced data structure #algorithms #arrays #competitive programming #recursion #tree #array-range-queries #segment-tree