SlideShare a Scribd company logo
1 of 4
Download to read offline
Square Root Decompostion
Square Root Decomposition is a technique used by competitve programmers as
the most common query optimization technique.This method is allow us to
perfor some common operations(finding some of the element of given sub-array,
finding the min / max element etc.) in O(sqrt(n)).Which is way more faster
than naive O(n) approach.
The key idea of this technique is decompose the original array into smaller
chunks specifically sqrt(n).
Lets say we have an array of n=9 elements and we decompose this array into
small chunks of size sqrt(n).
index :
Elements :
Here , n=9
So, ceil(sqrt(n)) = 3
This means we are going to decompose this array into 3 chunks and every chunks
will have a precomputed value of query we need to perform.
Suppose we are finding the sum of a range between l , r.
Then the decomposed array will save those sums for us to get further result
from it.
index :
Elements :
Block - 0 Block - 1 Block - 2
Decomposed Array
How we know which block is contain which range ??
We simply can divide the index with sqrt(n).Which is in this case 3.
So ,
0 / 3 = 0 (block - 0)
1 / 3 = 0 (block - 0)
4 / 3 = 1 (block - 1)
8 / 3 = 2 (block - 2) ans so on.
Query range types
index :
Elements :
Block - 0 Block - 1 Block - 2
Decomposed Array
Given Range is in block boundaries
l = 0 , r = 5
l = 3 , r = 5
In this type , the range may cover the blocks evenly and we can answer it by
summing up the completely overlapped blcock.
As example,
l = 0 , r = 5
this query totally overlapped the block 0,1.
So the ans would be decompose[0] + decompose[1] = 12
we get the result in just 2 step where in naive approach you will
need atlest 6 in this query.
Time complexity of this in worst case the range can be
l = 0 , r = n - 1
so , we need to sum up sqrt(n) blocks
as a result the complexity becomes O(sqrt(n))
Given Range is not in block boundaries
index :
Elements :
Block - 0 Block - 1 Block - 2
Decomposed Array
l = 1 , r = 6
l = 4 , r = 7
In this type , we can sum up the overlapped parts from the decomposed array and
some tail values from the original array.
as example , l = 1 , r = 6
see, in this segment , from 3 to 5 resides in block-1
we can add the decompose[1] with our answer
and from start, index 1 , 2 are calculated from orignal array
so answer becomes ans = decompose[1] + original[1] + original[2]
and from end, index 6 calculated from original.
as final result
ans = decompose[1] + original[1] + original[2] + original[6]
ans = 4 + 2 + 1 + 4
ans = 11
Time complexity of this in worst case can be like
l = 1 , r = n - 2;
this means the number of overlapped blocks is sqrt(n)-2 bc the first
and last block is partial here.
so to calculate the overlapped parts we need,
** sqrt(n)-2 ~ sqrt(n) time.
and to calculate the first and last partial blocks
we need to go through sqrt(n) - 1 elements from the original array.
so from both side,
** sqrt(n)-1 + sqrt(n)-1
so finally,
overlapped blocks + front non partial blocks + back non partial blocks
= sqrt(n) + sqrt(n) + sqrt(n)
= 3 * sqrt(n) ~ sqrt(n).
Implementation :
//preprocess the decomposed array

More Related Content

What's hot

Proof of O(log *n) time complexity of Union find (Presentation by Wei Li, Zeh...
Proof of O(log *n) time complexity of Union find (Presentation by Wei Li, Zeh...Proof of O(log *n) time complexity of Union find (Presentation by Wei Li, Zeh...
Proof of O(log *n) time complexity of Union find (Presentation by Wei Li, Zeh...Amrinder Arora
 
Chapter 2 inverse_trigonometric_functions
Chapter 2 inverse_trigonometric_functionsChapter 2 inverse_trigonometric_functions
Chapter 2 inverse_trigonometric_functionsShahrukh Javed
 
NEW NON-COPRIME CONJUGATE-PAIR BINARY TO RNS MULTI-MODULI FOR RESIDUE NUMBER ...
NEW NON-COPRIME CONJUGATE-PAIR BINARY TO RNS MULTI-MODULI FOR RESIDUE NUMBER ...NEW NON-COPRIME CONJUGATE-PAIR BINARY TO RNS MULTI-MODULI FOR RESIDUE NUMBER ...
NEW NON-COPRIME CONJUGATE-PAIR BINARY TO RNS MULTI-MODULI FOR RESIDUE NUMBER ...csandit
 
LeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfLeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfzupsezekno
 
The 2 Goldbach's Conjectures with Proof
The 2 Goldbach's Conjectures with Proof The 2 Goldbach's Conjectures with Proof
The 2 Goldbach's Conjectures with Proof nikos mantzakouras
 
finding Min and max element from given array using divide & conquer
finding Min and max element from given array using  divide & conquer finding Min and max element from given array using  divide & conquer
finding Min and max element from given array using divide & conquer Swati Kulkarni Jaipurkar
 
Aplikasi Bilangan Kompleks - Analisis Sinyal [PAPER]
Aplikasi Bilangan Kompleks - Analisis Sinyal [PAPER]Aplikasi Bilangan Kompleks - Analisis Sinyal [PAPER]
Aplikasi Bilangan Kompleks - Analisis Sinyal [PAPER]Ghins GO
 
Job sequencing with deadlines(with example)
Job sequencing with deadlines(with example)Job sequencing with deadlines(with example)
Job sequencing with deadlines(with example)Vrinda Sheela
 
Daa unit 6_efficiency of algorithms
Daa unit 6_efficiency of algorithmsDaa unit 6_efficiency of algorithms
Daa unit 6_efficiency of algorithmssnehajiyani
 
design and analysis of algorithm
design and analysis of algorithmdesign and analysis of algorithm
design and analysis of algorithmMuhammad Arish
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back trackingTech_MX
 

What's hot (20)

Proof of O(log *n) time complexity of Union find (Presentation by Wei Li, Zeh...
Proof of O(log *n) time complexity of Union find (Presentation by Wei Li, Zeh...Proof of O(log *n) time complexity of Union find (Presentation by Wei Li, Zeh...
Proof of O(log *n) time complexity of Union find (Presentation by Wei Li, Zeh...
 
Chapter 2 inverse_trigonometric_functions
Chapter 2 inverse_trigonometric_functionsChapter 2 inverse_trigonometric_functions
Chapter 2 inverse_trigonometric_functions
 
Daa unit 2
Daa unit 2Daa unit 2
Daa unit 2
 
NEW NON-COPRIME CONJUGATE-PAIR BINARY TO RNS MULTI-MODULI FOR RESIDUE NUMBER ...
NEW NON-COPRIME CONJUGATE-PAIR BINARY TO RNS MULTI-MODULI FOR RESIDUE NUMBER ...NEW NON-COPRIME CONJUGATE-PAIR BINARY TO RNS MULTI-MODULI FOR RESIDUE NUMBER ...
NEW NON-COPRIME CONJUGATE-PAIR BINARY TO RNS MULTI-MODULI FOR RESIDUE NUMBER ...
 
LeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfLeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdf
 
The 2 Goldbach's Conjectures with Proof
The 2 Goldbach's Conjectures with Proof The 2 Goldbach's Conjectures with Proof
The 2 Goldbach's Conjectures with Proof
 
finding Min and max element from given array using divide & conquer
finding Min and max element from given array using  divide & conquer finding Min and max element from given array using  divide & conquer
finding Min and max element from given array using divide & conquer
 
Aplikasi Bilangan Kompleks - Analisis Sinyal [PAPER]
Aplikasi Bilangan Kompleks - Analisis Sinyal [PAPER]Aplikasi Bilangan Kompleks - Analisis Sinyal [PAPER]
Aplikasi Bilangan Kompleks - Analisis Sinyal [PAPER]
 
Job sequencing with deadlines(with example)
Job sequencing with deadlines(with example)Job sequencing with deadlines(with example)
Job sequencing with deadlines(with example)
 
5.1 greedy
5.1 greedy5.1 greedy
5.1 greedy
 
Hbam2011 09
Hbam2011 09Hbam2011 09
Hbam2011 09
 
Daa unit 6_efficiency of algorithms
Daa unit 6_efficiency of algorithmsDaa unit 6_efficiency of algorithms
Daa unit 6_efficiency of algorithms
 
design and analysis of algorithm
design and analysis of algorithmdesign and analysis of algorithm
design and analysis of algorithm
 
Algorithms
AlgorithmsAlgorithms
Algorithms
 
Chap05alg
Chap05algChap05alg
Chap05alg
 
Backtracking
BacktrackingBacktracking
Backtracking
 
1639 vector-linear algebra
1639 vector-linear algebra1639 vector-linear algebra
1639 vector-linear algebra
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back tracking
 
Alg2 lesson 4-7
Alg2 lesson 4-7Alg2 lesson 4-7
Alg2 lesson 4-7
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 

Similar to Square Root Decomposition

pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqPradeep Bisht
 
M269 Data Structures And Computability.docx
M269 Data Structures And Computability.docxM269 Data Structures And Computability.docx
M269 Data Structures And Computability.docxstirlingvwriters
 
Answers withexplanations
Answers withexplanationsAnswers withexplanations
Answers withexplanationsGopi Saiteja
 
Algorithms presentation on Path Matrix, Bell Number and Sorting
Algorithms presentation on Path Matrix, Bell Number and SortingAlgorithms presentation on Path Matrix, Bell Number and Sorting
Algorithms presentation on Path Matrix, Bell Number and SortingRishabh Mehan
 
shell and merge sort
shell and merge sortshell and merge sort
shell and merge sorti i
 
Skiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortSkiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortzukun
 
algorithm assignmenteeeeeee.pptx
algorithm assignmenteeeeeee.pptxalgorithm assignmenteeeeeee.pptx
algorithm assignmenteeeeeee.pptxkassahungebrie
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingzukun
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updatedvrgokila
 
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfUnit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfyashodamb
 
Permutations and Combinations IIT JEE+Olympiad Lecture 4
Permutations and Combinations IIT JEE+Olympiad Lecture 4Permutations and Combinations IIT JEE+Olympiad Lecture 4
Permutations and Combinations IIT JEE+Olympiad Lecture 4Parth Nandedkar
 
6.sequences and series Further Mathematics Zimbabwe Zimsec Cambridge
6.sequences and series   Further Mathematics Zimbabwe Zimsec Cambridge6.sequences and series   Further Mathematics Zimbabwe Zimsec Cambridge
6.sequences and series Further Mathematics Zimbabwe Zimsec Cambridgealproelearning
 
Find the compact trigonometric Fourier series for the periodic signal.pdf
Find the compact trigonometric Fourier series for the periodic signal.pdfFind the compact trigonometric Fourier series for the periodic signal.pdf
Find the compact trigonometric Fourier series for the periodic signal.pdfarihantelectronics
 

Similar to Square Root Decomposition (20)

Rsa encryption
Rsa encryptionRsa encryption
Rsa encryption
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conq
 
M269 Data Structures And Computability.docx
M269 Data Structures And Computability.docxM269 Data Structures And Computability.docx
M269 Data Structures And Computability.docx
 
Data structure algorithm
Data structure algorithmData structure algorithm
Data structure algorithm
 
Answers withexplanations
Answers withexplanationsAnswers withexplanations
Answers withexplanations
 
Algorithms presentation on Path Matrix, Bell Number and Sorting
Algorithms presentation on Path Matrix, Bell Number and SortingAlgorithms presentation on Path Matrix, Bell Number and Sorting
Algorithms presentation on Path Matrix, Bell Number and Sorting
 
shell and merge sort
shell and merge sortshell and merge sort
shell and merge sort
 
Ch07 linearspacealignment
Ch07 linearspacealignmentCh07 linearspacealignment
Ch07 linearspacealignment
 
Skiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortSkiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksort
 
algorithm assignmenteeeeeee.pptx
algorithm assignmenteeeeeee.pptxalgorithm assignmenteeeeeee.pptx
algorithm assignmenteeeeeee.pptx
 
Daa chapter 2
Daa chapter 2Daa chapter 2
Daa chapter 2
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sorting
 
Sorting
SortingSorting
Sorting
 
2ds
2ds2ds
2ds
 
Unit 2 in daa
Unit 2 in daaUnit 2 in daa
Unit 2 in daa
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
 
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfUnit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
 
Permutations and Combinations IIT JEE+Olympiad Lecture 4
Permutations and Combinations IIT JEE+Olympiad Lecture 4Permutations and Combinations IIT JEE+Olympiad Lecture 4
Permutations and Combinations IIT JEE+Olympiad Lecture 4
 
6.sequences and series Further Mathematics Zimbabwe Zimsec Cambridge
6.sequences and series   Further Mathematics Zimbabwe Zimsec Cambridge6.sequences and series   Further Mathematics Zimbabwe Zimsec Cambridge
6.sequences and series Further Mathematics Zimbabwe Zimsec Cambridge
 
Find the compact trigonometric Fourier series for the periodic signal.pdf
Find the compact trigonometric Fourier series for the periodic signal.pdfFind the compact trigonometric Fourier series for the periodic signal.pdf
Find the compact trigonometric Fourier series for the periodic signal.pdf
 

Recently uploaded

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingWSO2
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringWSO2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceIES VE
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformWSO2
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfdanishmna97
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaWSO2
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...caitlingebhard1
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 

Recently uploaded (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 

Square Root Decomposition

  • 1. Square Root Decompostion Square Root Decomposition is a technique used by competitve programmers as the most common query optimization technique.This method is allow us to perfor some common operations(finding some of the element of given sub-array, finding the min / max element etc.) in O(sqrt(n)).Which is way more faster than naive O(n) approach. The key idea of this technique is decompose the original array into smaller chunks specifically sqrt(n). Lets say we have an array of n=9 elements and we decompose this array into small chunks of size sqrt(n). index : Elements : Here , n=9 So, ceil(sqrt(n)) = 3 This means we are going to decompose this array into 3 chunks and every chunks will have a precomputed value of query we need to perform. Suppose we are finding the sum of a range between l , r. Then the decomposed array will save those sums for us to get further result from it. index : Elements : Block - 0 Block - 1 Block - 2 Decomposed Array
  • 2. How we know which block is contain which range ?? We simply can divide the index with sqrt(n).Which is in this case 3. So , 0 / 3 = 0 (block - 0) 1 / 3 = 0 (block - 0) 4 / 3 = 1 (block - 1) 8 / 3 = 2 (block - 2) ans so on. Query range types index : Elements : Block - 0 Block - 1 Block - 2 Decomposed Array Given Range is in block boundaries l = 0 , r = 5 l = 3 , r = 5 In this type , the range may cover the blocks evenly and we can answer it by summing up the completely overlapped blcock. As example, l = 0 , r = 5 this query totally overlapped the block 0,1. So the ans would be decompose[0] + decompose[1] = 12 we get the result in just 2 step where in naive approach you will need atlest 6 in this query.
  • 3. Time complexity of this in worst case the range can be l = 0 , r = n - 1 so , we need to sum up sqrt(n) blocks as a result the complexity becomes O(sqrt(n)) Given Range is not in block boundaries index : Elements : Block - 0 Block - 1 Block - 2 Decomposed Array l = 1 , r = 6 l = 4 , r = 7 In this type , we can sum up the overlapped parts from the decomposed array and some tail values from the original array. as example , l = 1 , r = 6 see, in this segment , from 3 to 5 resides in block-1 we can add the decompose[1] with our answer and from start, index 1 , 2 are calculated from orignal array so answer becomes ans = decompose[1] + original[1] + original[2] and from end, index 6 calculated from original. as final result ans = decompose[1] + original[1] + original[2] + original[6] ans = 4 + 2 + 1 + 4 ans = 11
  • 4. Time complexity of this in worst case can be like l = 1 , r = n - 2; this means the number of overlapped blocks is sqrt(n)-2 bc the first and last block is partial here. so to calculate the overlapped parts we need, ** sqrt(n)-2 ~ sqrt(n) time. and to calculate the first and last partial blocks we need to go through sqrt(n) - 1 elements from the original array. so from both side, ** sqrt(n)-1 + sqrt(n)-1 so finally, overlapped blocks + front non partial blocks + back non partial blocks = sqrt(n) + sqrt(n) + sqrt(n) = 3 * sqrt(n) ~ sqrt(n). Implementation : //preprocess the decomposed array