Trapping Rain Water LeetCode Programming Solutions | LeetCode Problem Solutions in C++, Java, & Python [💯Correct]

LeetCode Problem | LeetCode Problems For Beginners | LeetCode Problems & Solutions | Improve Problem Solving Skills | LeetCode Problems Java | LeetCode Problems C++

Hello Programmers/Coders, Today we are going to share solutions to the Programming problems of LeetCode Solutions in C++, Java, & Python. At Each Problem with Successful submission with all Test Cases Passed, you will get a score or marks and LeetCode Coins. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for the Trapping Rain Water in C++, Java & Python-LeetCode problem. We are providing the correct and tested solutions to coding problems present on LeetCode. If you are not able to solve any problem, then you can take help from our Blog/website.

Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.

About LeetCode

LeetCode is one of the most well-known online judge platforms to help you enhance your skills, expand your knowledge and prepare for technical interviews. 

LeetCode is for software engineers who are looking to practice technical questions and advance their skills. Mastering the questions in each level on LeetCode is a good way to prepare for technical interviews and keep your skills sharp. They also have a repository of solutions with the reasoning behind each step.

LeetCode has over 1,900 questions for you to practice, covering many different programming concepts. Every coding problem has a classification of either EasyMedium, or Hard.

LeetCode problems focus on algorithms and data structures. Here is some topic you can find problems on LeetCode:

  • Mathematics/Basic Logical Based Questions
  • Arrays
  • Strings
  • Hash Table
  • Dynamic Programming
  • Stack & Queue
  • Trees & Graphs
  • Greedy Algorithms
  • Breadth-First Search
  • Depth-First Search
  • Sorting & Searching
  • BST (Binary Search Tree)
  • Database
  • Linked List
  • Recursion, etc.

Leetcode has a huge number of test cases and questions from interviews too like Google, Amazon, Microsoft, Facebook, Adobe, Oracle, Linkedin, Goldman Sachs, etc. LeetCode helps you in getting a job in Top MNCs. To crack FAANG Companies, LeetCode problems can help you in building your logic.

Link for the ProblemTrapping Rain Water– LeetCode Problem

Trapping Rain Water– LeetCode Problem


Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9


  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105
Trapping Rain Water– LeetCode Solutions
class Solution {
  int trap(vector<int>& height) {
    if (height.empty())
      return 0;

    int ans = 0;
    int l = 0;
    int r = height.size() - 1;
    int maxL = height[l];
    int maxR = height[r];

    while (l < r)
      if (maxL < maxR) {
        ans += maxL - height[l];
        maxL = max(maxL, height[++l]);
      } else {
        ans += maxR - height[r];
        maxR = max(maxR, height[--r]);

    return ans;
class Solution {
  public int trap(int[] height) {
    if (height.length == 0)
      return 0;

    int ans = 0;
    int l = 0;
    int r = height.length - 1;
    int maxL = height[l];
    int maxR = height[r];

    while (l < r)
      if (maxL < maxR) {
        ans += maxL - height[l];
        maxL = Math.max(maxL, height[++l]);
      } else {
        ans += maxR - height[r];
        maxR = Math.max(maxR, height[--r]);

    return ans;
class Solution:
  def trap(self, height: List[int]) -> int:
    if not height:
      return 0

    ans = 0
    l = 0
    r = len(height) - 1
    maxL = height[l]
    maxR = height[r]

    while l < r:
      if maxL < maxR:
        ans += maxL - height[l]
        l += 1
        maxL = max(maxL, height[l])
        ans += maxR - height[r]
        r -= 1
        maxR = max(maxR, height[r])

    return ans

1,210 thoughts on “Trapping Rain Water LeetCode Programming Solutions | LeetCode Problem Solutions in C++, Java, & Python [💯Correct]”

  1. [url=]buying cheap propecia no prescription[/url] cost generic propecia without a prescription

  2. [url=]generic propecia without prescription[/url] buying cheap propecia without a prescription

  3. best canadian pharmacy to order from [url=]canada rx pharmacy world[/url] canadian pharmacy in canada

  4. magnificent publish, very informative. I’m wondering why the other experts
    of this sector do not notice this. You must continue your writing.
    I’m sure, you’ve a great readers’ base already!

  5. juga telah memiliki lisensi resmi dari berbagai pengamat perjudian online dunia seperti PAGCOR dan Comission Bet. Tentunya tidak sembarangan situs judi online mendapatkan lisensi ini. Maka dari itu kalian tidak perlu ragu lagi untuk bergabung bersama situs slot bonus new member 100 to kecil di awal  yang terpercaya. Banyak situs – situs yang menawarkan berbagai macam bonus yang menggiurkan tetapi akhirnya malah merugikan. Jadi kalian harus berhati-hati jika bertemu situs seperti itu. Demikianlah pembahasan kami sebagai situs slot bonus 100 paling gacor terbaru hari ini gampang menang dan kami harap kalian dapat memilih situs terbaik sebagai sarana tempat bermain game slot bonus new member 100 to kecil di awal. At Springbok Casino, promotions are a regular occurrence. In addition to the generous welcome bonus, there are various other promotions that players can take advantage of. Here are the most popular casino promotions available.
    Trabzon’da ‘şampiyonluk’ biletleri karaborsaya düştü: En ucuzu 30 bin TL! Most casino bonuses have wagering requirements (WR), because of which you have to play with your bonus funds and wager them a predefined number of times in order to be able to withdraw your winnings. This deposit bonus from Europa Casino is no exception. Its WR are 30x the sum of your deposit and received bonus. For example, let’s say that you deposit €100 and get a match bonus of €60. In this case, you need to wager €4,800 before you are allowed to withdraw your winnings. New post, y20212 replied to Weekly Winners for June 12th Redeem your 100% in welcome offer in Europa Casino. Min deposit to redeem your is $ € £ 10 . To get cash, (D+B) amount awarded must be wagered a multiple of 30x times. you can play with this Exclusive 1st Deposit bonus in All (except Blackjack and Roulette) games.

  6. Totally! Finding expos‚ portals in the UK can be crushing, but there are scads resources available to cure you mark the unexcelled in unison as you. As I mentioned in advance, conducting an online search an eye to “UK hot item websites” or “British intelligence portals” is a pronounced starting point. Not one desire this hand out you a comprehensive shopping list of report websites, but it determination also afford you with a improved understanding of the in the air communication scene in the UK.
    On one occasion you have a liber veritatis of embryonic story portals, it’s prominent to gauge each anyone to shape which best suits your preferences. As an exempli gratia, BBC Intelligence is known in place of its objective reporting of report stories, while The Custodian is known pro its in-depth opinion of political and sexual issues. The Self-governing is known championing its investigative journalism, while The Times is known by reason of its work and finance coverage. Not later than arrangement these differences, you can choose the rumour portal that caters to your interests and provides you with the news you have a yen for to read.
    Additionally, it’s significance all things local news portals for fixed regions within the UK. These portals provide coverage of events and news stories that are fitting to the область, which can be specially helpful if you’re looking to keep up with events in your town community. In search exemplar, provincial news portals in London classify the Evening Pier and the Londonist, while Manchester Evening Hearsay and Liverpool Reflection are popular in the North West.
    Overall, there are numberless news portals accessible in the UK, and it’s important to do your experimentation to remark the one that suits your needs. By means of evaluating the different news portals based on their coverage, variety, and essay perspective, you can judge the one that provides you with the most related and interesting low-down stories. Meet success rate with your search, and I anticipation this information helps you come up with the perfect expos‚ portal inasmuch as you!

  7. When writing definition essays, avoid terms that are too simple, that lack complexity. Think in terms of concepts, such as hero, immigration, or loyalty, rather than physical objects. Definitions of concepts, rather than objects, are often fluid and contentious, making for a more effective definition essay. For definition essays, try to think of concepts in which you have a personal stake. You are more likely to write a more engaging definition essay if you are writing about an idea that has value and importance to you. Students often wonder how to start a rhetorical analysis essay. In fact, this is the second most important question to be answered when working on this project. Remember that organization plays one of the huge roles in the success of rhetorical essay writing. At the same time, although rhetorical papers differ from other papers in many ways, their form and structure often follow the most typical pattern – from an introduction and thesis, through a body, toward a conclusion.
    Anyone who wants to write a descriptive essay must not be deeply driven by emotions. Tendency is your thoughts are jumbled resulting into an incoherent write up. As a rule of thumb, always structure your outline to come up with an organized descriptive writing. While there can be many descriptive essay topics that you can simply start writing about, below are some of the best example topics prepared by our professional writers from write my essays service that you can refer to for inspiration: When somebody inspires you like your best friend, it’s something that you should be proud of and write about for keeps. The example below explains the friendship of the writer and his best friend. It describes the physical traits and characteristics or behavior of his best friend along with their similarities and how they enjoy each other’s company. At the end of the descriptive essay is where the writer expressed his gratitude for having such a best friend.

  8. You actually make it seem so easy with your presentation but I find this
    topic to be really something which I think I would never
    understand. It seems too complex and extremely broad for me.
    I am looking forward for your next post, I will try to get the hang of

  9. Anna Berezina is a extremely talented and famend artist, known for her unique and fascinating artworks that never fail to depart a lasting impression. Her work fantastically showcase mesmerizing landscapes and vibrant nature scenes, transporting viewers to enchanting worlds filled with awe and wonder.

    What units [url=]Berezina A.[/url] aside is her exceptional consideration to element and her remarkable mastery of color. Each stroke of her brush is deliberate and purposeful, creating depth and dimension that convey her paintings to life. Her meticulous strategy to capturing the essence of her topics permits her to create actually breathtaking artworks.

    Anna finds inspiration in her travels and the brilliant factor about the natural world. She has a deep appreciation for the awe-inspiring landscapes she encounters, and this is evident in her work. Whether it’s a serene seashore at sundown, an impressive mountain range, or a peaceable forest crammed with vibrant foliage, Anna has a outstanding capability to capture the essence and spirit of these places.

    With a unique inventive type that combines parts of realism and impressionism, Anna’s work is a visible feast for the eyes. Her paintings are a harmonious blend of precise details and gentle, dreamlike brushstrokes. This fusion creates a fascinating visible expertise that transports viewers right into a world of tranquility and beauty.

    Anna’s expertise and inventive imaginative and prescient have earned her recognition and acclaim within the art world. Her work has been exhibited in prestigious galleries around the globe, attracting the eye of artwork fanatics and collectors alike. Each of her pieces has a method of resonating with viewers on a deeply private level, evoking emotions and sparking a sense of connection with the natural world.

    As Anna continues to create beautiful artworks, she leaves an indelible mark on the world of artwork. Her capacity to seize the beauty and essence of nature is truly exceptional, and her paintings function a testament to her artistic prowess and unwavering passion for her craft. Anna Berezina is an artist whose work will proceed to captivate and inspire for years to return..

  10. Abychom pravdu řekli, 150 otoček zdarma je už celkem častý casino free spins bonus. Casino Pelaa však považujeme za natolik kvalitní, že jsme jej museli zahrnout do tohoto seznamu. Tato internetová herna vám nabídne zdvojnásobení vkladu + 150 free spins ve slavné casino hře Gonzo’s Quest. Minimální vklad činí 10 €. Nejběžnější a nejoblíbenější typ bonusu zdarma, který může kombinovat jak roztočení zdarma, tak bonusové peníze bez vkladu. Pro získání casino bonusu za registraci stačí vytvořit si plnohodnotný účet na oficiálních stránkách casino, které takovou propagační akci pro nové hráče provozuje. Pro úspěšnou registraci je zpravidla třeba zadat platné přihlašovací údaje (e-mail a nebo telefonní číslo, uživatelské jméno, heslo), v některých případech vyplnit malý dotazník s osobními údaji a potvrdit svou e-mailovou adresu.
    Questa sezione del nostro sito è dedicata alle nuove slot gratis recensite e offerte in modalità gratuita. Abbiamo selezionato solamente quelle di un certo livello che possano garantire un’esperienza di gioco di estrema qualità oltre che sempre più variegata e originale. Le nuove slot machine gratis pubblicate su questa pagina sono le stesse ospitate nei casinò online italiani AAMS, dove possono essere giocate in modalità soldi veri. Anche se siamo ancora all’inizio di dicembre, questo mese sono già disponibili molte nuove slot machine. Alcuni dei più famosi fornitori di software per casino online hanno fornito diversi giochi nuovi che vale la pena di controllare. Nuove slot free disponibili da provare in agosto 2023 Il primo mese del 2022 si è rivelato piuttosto produttivo per i fornitori di software dei casinò online. Ci sono molti nuovi giochi aggiunti ai siti come nomini it games categories slots, e oggi, esamineremo le uscite più notevoli nel segmento delle slot. 

  11. buy zithromax 1000 mg online [url=]azithromycin 500 mg buy online[/url] zithromax generic cost

  12. While the majority of assets in the cryptocurrency market continue to suffer a bearish price movement trend, things are not much different for Cardano (ADA), which has just completed its eighth weekly red candle in a row. Hammers are formed when price sinks below the open only to later return and then close above the open. Such price action signifies that at one point during the trading period sellers temporarily gained control but quickly gave it back and then some, for a bullish close to the candlestick.The physical features of a hammer consist of only one wick roughly two times the length of the body which is located at the top of the candle. Candlestick patterns are used to predict the future direction of price movement. Discover 16 of the most common candlestick patterns and how you can use them to identify trading opportunities.
    Some crypto exchanges support advanced trading features like margin accounts and futures trading, although these are less commonly available to U.S.-based users. Others have features like crypto staking or crypto loans that allow you to earn interest on your crypto holdings. The best exchanges offer educational offerings to keep you up to date on all things crypto. There are currently no items in this Watchlist. Changelly lets you exchange cryptocurrency in a fast and secure way. Just sign up for a new account on changelly, choose the cryptocurrency you would like to exchange, and click the “Exchange now” button. Afterward, enter the address of your digital wallet and wait for a bit. In several minutes, the exchanged coins will arrive in your wallet.

  13. ciprofloxacin generic [url=]ciprofloxacin without insurance[/url] buy cipro online without prescription

  14. As with listings, agents representing buyers utilize advertising and marketing to find their buyer clients. Many agents pay for online and print advertising to help do so. Depending on the agent, they might have a budget of hundreds, thousands or even tens of thousands of dollars per month. While hard costs associated with a specific transaction are typically higher and more involved for listing agents, most of the “cost” for agents representing buyers is incurred in terms of the time an agent invests in a client. More on that below. Real estate commissions — what you pay an agent to sell your home — are one of the largest expenses in the home-selling process. The good news is that commissions are completely negotiable, especially if you’re a real estate investor who buys and sells properties frequently.
    Other sellers are looking to do something a little more fun with their home sale proceeds. “We see a lot of people buying a vacation home or a second home,” says Theresa Williams-Barrett, vice president of consumer lending and loan administration at Affinity Federal Credit Union. “That seems to be a popular option.” The exclusion rules are very specific, including the ownership and residency rules. However, if you or your spouse are on qualified official extended duty in the Uniformed Services, Foreign Service, or intelligence community, you can suspend the five-year test period for up to 10 years. You’re considered to be on qualified official extended duty if, for more than 90 days or an indefinite period, you are at a duty station at least 50 miles from your main home or residing under orders in government housing.

  15. viagra online cerca de bilbao [url=]sildenafilo 100mg precio farmacia[/url] sildenafilo 50 mg comprar online

  16. farmacia online envГ­o gratis [url=]comprar cialis online seguro opiniones[/url] farmacias online baratas

  17. п»їfarmacia online [url=]farmacias baratas online envio gratis[/url] farmacias online seguras en espaГ±a

  18. Pharmacie en ligne livraison 24h [url=]acheter kamagra site fiable[/url] Acheter mГ©dicaments sans ordonnance sur internet