question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
valid-phone-numbers
Bash cat grep
bash-cat-grep-by-ajrs-pc3p
\n# Read from the file file.txt and output all valid phone numbers to stdout.\ncat file.txt | grep -E "(^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\\([0-9]{3,3}\\) [0-9]{3}-
ajrs
NORMAL
2021-07-02T05:20:01.996842+00:00
2021-07-02T05:20:01.996879+00:00
906
false
```\n# Read from the file file.txt and output all valid phone numbers to stdout.\ncat file.txt | grep -E "(^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\\([0-9]{3,3}\\) [0-9]{3}-[0-9]{4}$)"\n```
2
0
[]
2
valid-phone-numbers
this solution can not be more uglier :( but hey at least it works : D
this-solution-can-not-be-more-uglier-but-j6li
\tpublic static boolean isValid(String num){\n\t\t\tnum.trim();\n\t\t\tString[] tokens0 = num.split(" +");\n\t\t\tif (tokens0.length == 3) {\n\t\t\t\treturn fal
jerryJv11
NORMAL
2020-11-27T03:35:42.332222+00:00
2020-11-27T03:35:42.332256+00:00
595
false
\tpublic static boolean isValid(String num){\n\t\t\tnum.trim();\n\t\t\tString[] tokens0 = num.split(" +");\n\t\t\tif (tokens0.length == 3) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tString[] tokens = num.split("\\\\-" );\n\t\t\tif (tokens.length == 3) {\n\t\t\t\tif (tokens[0].length() == 3 && tokens[1].length() == 3 && tokens[2].length() == 4 && onlyDigits(tokens[0]) && onlyDigits(tokens[1]) && onlyDigits(tokens[2])) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse return false;\n\n\t\t\t}\n\t\t\telse if (tokens.length == 2) {\n\t\t\t\tif (tokens[0].charAt(0) == \'(\' && tokens[0].charAt(4) == \')\' && onlyDigits(tokens[0].substring(1 , 4)) && onlyDigits(tokens[0].substring(6)) && onlyDigits(tokens[1])) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 0 ; i < tokens.length ; i++) {\n\t\t\t\tSystem.out.println(tokens[i]);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tpublic static boolean onlyDigits(String str) {\n\t\t\tfor (int i = 0; i < str.length(); i++) {\n\t\t\t\tif (str.charAt(i) >= \'0\'\n\t\t\t\t\t\t&& str.charAt(i) <= \'9\') return true;\n\t\t\t\telse return false;\n\t\t\t}\n\t\t\treturn false;\n\t\t}
2
0
[]
0
valid-phone-numbers
Grep -E approach simplified
grep-e-approach-simplified-by-spenz-kru5
\ngrep -E \'^([0-9]{3}\\-|\\([0-9]{3}\\) )[0-9]{3}\\-[0-9]{4}$\' file.txt\n
spenz
NORMAL
2020-05-08T06:21:58.559327+00:00
2020-05-08T06:21:58.559381+00:00
639
false
```\ngrep -E \'^([0-9]{3}\\-|\\([0-9]{3}\\) )[0-9]{3}\\-[0-9]{4}$\' file.txt\n```
2
0
[]
0
valid-phone-numbers
grep -e solution is pretty straightforward to me, why doesn't this work? Any ideas?
grep-e-solution-is-pretty-straightforwar-srq9
\ngrep -e "\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d" -e "(\\d\\d\\d) \\d\\d\\d-\\d\\d\\d\\d"\n\n
justxn
NORMAL
2019-07-28T06:55:58.441845+00:00
2019-07-28T06:55:58.441879+00:00
571
false
```\ngrep -e "\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d" -e "(\\d\\d\\d) \\d\\d\\d-\\d\\d\\d\\d"\n```\n
2
0
[]
1
valid-phone-numbers
grep -e solution
grep-e-solution-by-lei8c8yahoo-yivs
grep -e \'^[0-9]\\{3\\}-[0-9]\\{3\\}-[0-9]\\{4\\}$\' -e \'^([0-9]\\{3\\}) [0-9]\\{3\\}-[0-9]\\{4\\}$\' file.txt
lei8c8yahoo
NORMAL
2019-06-20T01:52:23.525375+00:00
2019-06-20T01:52:23.525422+00:00
736
false
```grep -e \'^[0-9]\\{3\\}-[0-9]\\{3\\}-[0-9]\\{4\\}$\' -e \'^([0-9]\\{3\\}) [0-9]\\{3\\}-[0-9]\\{4\\}$\' file.txt```
2
0
[]
0
valid-phone-numbers
Using Bash regex
using-bash-regex-by-oxota-ro01
\n#!/usr/bin/env bash\n\nwhile read line; do\n if [[ "$line" =~ ^((\\([0-9]{3}\\) )|[0-9]{3}-)[0-9]{3}-[0-9]{4}$ ]]; then\n echo $line\n fi\ndone <
oxota
NORMAL
2019-06-07T05:45:35.421290+00:00
2019-06-07T05:45:35.421321+00:00
822
false
```\n#!/usr/bin/env bash\n\nwhile read line; do\n if [[ "$line" =~ ^((\\([0-9]{3}\\) )|[0-9]{3}-)[0-9]{3}-[0-9]{4}$ ]]; then\n echo $line\n fi\ndone < "file.txt"\n```
2
0
[]
0
valid-phone-numbers
Why is `grep -E '^\(\d{3}\) \d{3}-\d{4}$|^\d{3}-\d{3}-\d{4}$' file.txt ` wrong?
why-is-grep-e-d3-d3-d4d3-d3-d4-filetxt-w-83an
\ngrep -E \'^\\(\\d{3}\\) \\d{3}-\\d{4}$|^\\d{3}-\\d{3}-\\d{4}$\' file.txt\n\n\nError message:\n\n\nInput:\n123-456-7891\nExpected:\n123-456-7891\n\n\n\nHowever
tylerlong
NORMAL
2018-05-29T08:53:41.960391+00:00
2018-05-29T08:53:41.960391+00:00
565
false
```\ngrep -E \'^\\(\\d{3}\\) \\d{3}-\\d{4}$|^\\d{3}-\\d{3}-\\d{4}$\' file.txt\n```\n\nError message:\n\n```\nInput:\n123-456-7891\nExpected:\n123-456-7891\n```\n\n\nHowever, the following works:\n\n```\ngrep -E \'^\\([0-9]{3}\\)\\s[0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$\' file.txt\n```\n\nThe only difference is `[0-9]` instead of `\\d`.\n\nOn my laptop (macOS), both work.
2
0
[]
3
valid-phone-numbers
Filter Valid Phone Numbers Using grep and Regular Expressions
filter-valid-phone-numbers-using-grep-an-nyss
IntuitionThe problem is essentially about filtering lines that match specific phone number formats. Since the input is a plain text file and the pattern is well
suhrob_kalandarov
NORMAL
2025-04-10T03:44:55.887697+00:00
2025-04-10T03:52:54.938301+00:00
38
false
# Intuition The problem is essentially about filtering lines that match specific phone number formats. Since the input is a plain text file and the pattern is well-defined, a regular expression is the most efficient tool to recognize valid formats. # Approach We use the grep command with the -E flag (extended regular expressions) to match phone numbers that follow either of these valid formats: 1. (xxx) xxx-xxxx 2. xxx-xxx-xxxx Our regular expression uses: - ^ and $ to ensure the entire line matches - \( and \) to match literal parentheses - [0-9]{3} and [0-9]{4} to match groups of digits - | to allow either format # Complexity - Time complexity: 𝑂(𝑛) — where n is the number of lines in the file. We process each line exactly once. - Space complexity: 𝑂(1) — we only store the current line being checked. # Code Beats 98.04% ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -P '^(\(\d{3}\) \d{3}-\d{4}|\d{3}-\d{3}-\d{4})$' file.txt ``` # Code Beats 100% ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. p=\([0-9][0-9][0-9]\)\ [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9] p1=[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9] while read -r line do case "$line" in $p) echo $line ;; $p1) echo $line ;; esac done < file.txt ``` ```
1
0
['Bash']
1
valid-phone-numbers
easy bash solution to understand
easy-bash-solution-to-understand-by-prat-wr9v
IntuitionApproachComplexity Time complexity: Space complexity: Code
pratik5722
NORMAL
2025-03-03T07:57:49.434122+00:00
2025-03-03T07:57:49.434122+00:00
450
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -E '^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\([0-9]{3}\)[[:space:]][0-9]{3}-[0-9]{4} ``` file.txt ```
1
0
['Bash']
0
valid-phone-numbers
Easy Solution Beats 98.24%
easy-solution-beats-9824-by-rishabh_234-02q1
PLEASE UPVOTE\n# FEEL FREE TO ASK\n# Code\nbash []\n# Read from the file file.txt and output all valid phone numbers to stdout.\ngrep \'^\\([0-9]\\{3\\}-\\|([0-
r_90
NORMAL
2024-10-20T16:52:04.132218+00:00
2024-10-20T16:52:04.132242+00:00
21
false
# PLEASE UPVOTE\n# FEEL FREE TO ASK\n# Code\n```bash []\n# Read from the file file.txt and output all valid phone numbers to stdout.\ngrep \'^\\([0-9]\\{3\\}-\\|([0-9]\\{3\\}) \\)[0-9]\\{3\\}-[0-9]\\{4\\}\n``` file.txt\n```
1
1
['Shell', 'Bash']
0
valid-phone-numbers
USING GREP COMMAND
using-grep-command-by-ujjwalvarma6948-kvfl
//PLEASE UPVOTE IF YOU LIKE THE APPRAOCH !!\n\n# Code\n\ngrep -e "^[0-9]\\{3\\}\\-[0-9]\\{3\\}\\-[0-9]\\{4\\}$" -e "^([0-9]\\{3\\}) [0-9]\\{3\\}\\-[0-9]\\{4\\}$
ujjwalvarma6948
NORMAL
2024-03-06T16:57:45.416155+00:00
2024-03-06T16:57:45.416187+00:00
553
false
//PLEASE UPVOTE IF YOU LIKE THE APPRAOCH !!\n\n# Code\n```\ngrep -e "^[0-9]\\{3\\}\\-[0-9]\\{3\\}\\-[0-9]\\{4\\}$" -e "^([0-9]\\{3\\}) [0-9]\\{3\\}\\-[0-9]\\{4\\}$" file.txt\n```
1
0
['Bash']
0
valid-phone-numbers
Number Validate
number-validate-by-abdulvoris-w1ja
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Abdulvoris
NORMAL
2024-01-10T19:20:25.190869+00:00
2024-01-10T19:20:25.190913+00:00
1,309
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#!/bin/bash\ngrep -E \'^\\([[:digit:]]{3}\\) [[:digit:]]{3}-[[:digit:]]{4}$|^[[:digit:]]{3}-[[:digit:]]{3}-[[:digit:]]{4}\n``` file.txt\n```
1
0
['Shell', 'Number Theory', 'Bash']
1
valid-phone-numbers
Solution
solution-by-suraj_singh_rajput-b8qe
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Suraj_singh_rajput
NORMAL
2023-12-22T07:11:38.010009+00:00
2023-12-22T07:11:38.010039+00:00
15
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Read from the file file.txt and output all valid phone numbers to stdout.\ngrep -E \'^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}\n``` file.txt\n\n```
1
0
['Bash']
0
valid-phone-numbers
Easy and simple :0 WOW (0_0)
easy-and-simple-0-wow-0_0-by-azamatabduv-deli
\n# Code\n\n# Read from the file file.txt and output all valid phone numbers to stdout.\ngrep -E \'^(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}\n file.txt\n```
AzamatAbduvohidov
NORMAL
2023-05-13T13:06:27.535847+00:00
2023-05-13T13:06:27.535877+00:00
6,992
false
\n# Code\n```\n# Read from the file file.txt and output all valid phone numbers to stdout.\ngrep -E \'^(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}\n``` file.txt\n```\nThis script uses grep command with extended regular expressions (-E) to match the pattern of valid phone numbers. The pattern matches either (xxx) xxx-xxxx or xxx-xxx-xxxx format. The ^ and $ characters are used to match the beginning and end of each line respectively13
1
0
['Bash']
1
valid-phone-numbers
[BASH] using while and if statements
bash-using-while-and-if-statements-by-am-icko
\n#!/bin/bash\nfile_name="file.txt"\nphone_number_regx=\'(^[0-9]{3}-[0-9]{3}-[0-9]{4}$)|(^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$)\'\n\nwhile read line;\ndo\n\tif [[
amresh564
NORMAL
2022-11-30T19:16:26.272570+00:00
2022-12-16T15:37:59.416202+00:00
136
false
```\n#!/bin/bash\nfile_name="file.txt"\nphone_number_regx=\'(^[0-9]{3}-[0-9]{3}-[0-9]{4}$)|(^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$)\'\n\nwhile read line;\ndo\n\tif [[ "$line" =~ $phone_number_regx ]]; then\n\t\techo $line\n\tfi\ndone<$file_name\n```
1
0
['Bash']
0
valid-phone-numbers
Simple Solution with grep - E with | (OR) | detail explanation
simple-solution-with-grep-e-with-or-deta-nuov
I just found this Blog and Github repository with solutions to Leetcode problems.\nhttps://leet-codes.blogspot.com\nIt is very useful, and I just wanted to shar
pmistry_
NORMAL
2022-09-03T14:59:10.745206+00:00
2022-10-12T15:06:32.927809+00:00
684
false
I just found this Blog and Github repository with solutions to Leetcode problems.\nhttps://leet-codes.blogspot.com\nIt is very useful, and I just wanted to share it with you.\nNote: You can bookmark it as a resource, and for another approaches\n<br>\n\n```\ngrep -E \'(^[0-9]{3}-|^\\([0-9]{3}\\) )[0-9]{3}-[0-9]{4}$\' file.txt\n```\n\nFor detail explnation please refer:\nhttps://leet-codes.blogspot.com/2022/09/193-valid-phone-numbers.html\n
1
0
[]
0
valid-phone-numbers
[Regex] Runtime: 649 ms, faster than 5.46% of Go submissions
regex-runtime-649-ms-faster-than-546-of-cry2s
Complexity Analysis\n Time: O(N), where N is the number of lines within the file.txt.\n Space: O(1), constant number of variables used.\n\nsh\nfunction isValid(
d8dca782
NORMAL
2022-07-18T00:34:59.821033+00:00
2022-07-18T00:34:59.821068+00:00
384
false
**Complexity Analysis**\n* Time: O(N), where N is the number of lines within the file.txt.\n* Space: O(1), constant number of variables used.\n\n```sh\nfunction isValid()\n{\n if [[ $1 =~ ^[0-9]{3}-[0-9]{3}-[0-9]{4}$ ]]; then\n return $(true)\n fi\n if [[ $1 =~ ^[(][0-9]{3}[)][[:space:]][0-9]{3}[-][0-9]{4}$ ]]; then\n return $(true)\n fi\n return $(false)\n}\n\nIFS=$\'\\n\'\nfor i in $(cat file.txt); do\n if isValid $i; then\n echo $i\n fi\ndone\n```
1
0
[]
0
valid-phone-numbers
One-Line Solution With Regex
one-line-solution-with-regex-by-jacdabro-uinm
Here is my solution:\n\n\n# Read from the file file.txt and output all valid phone numbers to stdout.\ngrep -E \'(^[0-9]{3}-|^\\([0-9]{3}\\) )[0-9]{3}-[0-9]{4}$
jacdabro
NORMAL
2022-07-05T15:05:39.688161+00:00
2022-07-05T16:13:24.440144+00:00
398
false
Here is my solution:\n\n```\n# Read from the file file.txt and output all valid phone numbers to stdout.\ngrep -E \'(^[0-9]{3}-|^\\([0-9]{3}\\) )[0-9]{3}-[0-9]{4}$\' file.txt\n```\n\nor \n\n```\ngrep -P \'^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$\' file.txt\n```
1
0
[]
1
valid-phone-numbers
[BASH] - Easy One Liner
bash-easy-one-liner-by-tursunboyevjahong-do0u
https://leetcode.com/problems/valid-phone-numbers/discuss/843424/BASH-Easy-One-Liner\n\n\n1) grep -P \'^(\\d{3}-\\d{3}-\\d{4}|\\(\\d{3}\\) \\d{3}-\\d{4})$\' fil
TursunboyevJahongir
NORMAL
2022-06-05T05:03:13.213097+00:00
2022-06-05T05:06:47.777270+00:00
847
false
https://leetcode.com/problems/valid-phone-numbers/discuss/843424/BASH-Easy-One-Liner\n\n```\n1) grep -P \'^(\\d{3}-\\d{3}-\\d{4}|\\(\\d{3}\\) \\d{3}-\\d{4})$\' file.txt\n```\n\n```\n2) grep -Po \'^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$\' file.txt\n```\n\n```\n3) egrep \'^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\\([0-9]{3}\\)\\s[0-9]{3}-[0-9]{4}$\' file.txt\n```
1
0
[]
0
valid-phone-numbers
Grep [Runtime: 4 ms Memory Usage: 3.1 MB]
grep-runtime-4-ms-memory-usage-31-mb-by-3ock2
\ngrep -Po \'^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$\' file.txt\n
ankitkumar734ac
NORMAL
2022-01-23T13:46:28.992062+00:00
2022-01-23T13:46:28.992106+00:00
440
false
```\ngrep -Po \'^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$\' file.txt\n```
1
0
[]
0
valid-phone-numbers
0ms solution. 100% faster!
0ms-solution-100-faster-by-akshayabee19-dupq
grep -P "^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$" file.txt
akshayabee19
NORMAL
2021-08-19T17:05:41.471313+00:00
2021-08-19T17:05:41.471359+00:00
1,015
false
```grep -P "^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$" file.txt```
1
0
[]
0
valid-phone-numbers
egrep solution with cat
egrep-solution-with-cat-by-letrounet-uasi
\ncat file.txt | egrep "^((\\([0-9]{3}\\) )|([0-9]{3}-))[0-9]{3}-{0,1}[0-9]{4}$"\n\n
letrounet
NORMAL
2021-07-20T00:53:07.820027+00:00
2021-07-20T00:53:07.820165+00:00
556
false
```\ncat file.txt | egrep "^((\\([0-9]{3}\\) )|([0-9]{3}-))[0-9]{3}-{0,1}[0-9]{4}$"\n```\n
1
0
[]
1
valid-phone-numbers
Egrep Solution
egrep-solution-by-souradeepsaha-zkn5
egrep "^([0-9]{3}-|\\([0-9]{3}\\) )[0-9]{3}-[0-9]{4}$" file.txt
souradeepsaha
NORMAL
2021-06-11T05:42:35.727198+00:00
2021-06-11T05:42:35.727233+00:00
365
false
```egrep "^([0-9]{3}-|\\([0-9]{3}\\) )[0-9]{3}-[0-9]{4}$" file.txt```
1
1
[]
0
valid-phone-numbers
No grep solution (actually works)
no-grep-solution-actually-works-by-maker-7q7c
It took me a while, as some attempts "work on my machine" but not here lol. I\'m sure this can be simplified, but it took me a few hours to get this to work, so
makerbro
NORMAL
2021-05-29T17:33:40.815417+00:00
2021-05-29T17:35:29.616511+00:00
626
false
It took me a while, as some attempts "work on my machine" but not here lol. I\'m sure this can be simplified, but it took me a few hours to get this to work, so will stop here and see if anyone out there improves upon it. Using a slightly shorter regex, and even looking at SO examples, people seem to not care about a number formatted like so `(123 456-7890` where one of the parentheses was missing. It wasn\'t part of the tested inputs, but I wanted to account for it as an exercise.\n\nSo, I just resorted to using the `|` (or) operator to check both formats. It was key to include `^$` both times as without it, the regex would match the number "0(001...".\n\n\n```\n#!/bin/bash\n\ncat file.txt | while read line\ndo\n if [[ "$line" =~ ^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\\([0-9]{3}\\)\\ [0-9]{3}-[0-9]{4}$ ]]; then\n echo $line\n fi \ndone\n```
1
0
[]
1
valid-phone-numbers
Quick grep solution
quick-grep-solution-by-lozuwaucb-r9pb
Check the number lengths, the tokens and make sure it starts and ends appropiately. \n\n\ncat file.txt | grep -Ei "^(\\([0-9]{3}\\)\\s[0-9]{3}-[0-9]{4}$)|^([0-9
lozuwaucb
NORMAL
2021-04-18T01:18:47.468668+00:00
2021-04-18T01:18:47.468699+00:00
773
false
Check the number lengths, the tokens and make sure it starts and ends appropiately. \n\n```\ncat file.txt | grep -Ei "^(\\([0-9]{3}\\)\\s[0-9]{3}-[0-9]{4}$)|^([0-9]{3}-[0-9]{3}-[0-9]{4}$)"\n```
1
1
[]
1
valid-phone-numbers
grep - P
grep-p-by-superroshan-22d7
grep -P "^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$" file.txt
superroshan
NORMAL
2021-01-21T05:18:45.605661+00:00
2021-01-21T05:19:44.072512+00:00
721
false
```grep -P "^(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}$" file.txt```
1
0
[]
0
valid-phone-numbers
Query related to input
query-related-to-input-by-_pii-cs5c
Can anyone tell me why this input is not valid \n(001)-345-0000\n\nthis is my bash one liner\ngrep -P \'^(\\(?\\d{3}|\\d{3})\\)?[\\s|-]\\d{3}-\\d{4}$\' file.txt
_pii_
NORMAL
2020-06-24T18:27:03.699601+00:00
2020-06-24T18:27:03.699645+00:00
355
false
Can anyone tell me why this input is not valid \n```(001)-345-0000```\n\nthis is my bash one liner\n```grep -P \'^(\\(?\\d{3}|\\d{3})\\)?[\\s|-]\\d{3}-\\d{4}$\' file.txt```\n\nit also accepts the above number but gets an error saying it should not get accepted\n
1
0
[]
1
valid-phone-numbers
grep -E
grep-e-by-gprx100-tjbr
```\ncat file.txt | grep -E "^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$"\n\n
gprx100
NORMAL
2020-04-12T21:49:03.574670+00:00
2020-04-12T21:49:03.574709+00:00
592
false
```\ncat file.txt | grep -E "^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$"\n\n
1
0
[]
0
valid-phone-numbers
mac bash or linux bash?
mac-bash-or-linux-bash-by-theosoft-ro89
At first, I use this code:\n\ncat file.txt | grep -E "^(\\d{3}-|\\(\\d{3}\\)\\ )\\d{3}-\\d{4}$"\n\nIt works in my mac bash shell, but failed for the submission.
theosoft
NORMAL
2020-03-27T13:45:38.099190+00:00
2020-03-27T13:45:38.099225+00:00
435
false
At first, I use this code:\n```\ncat file.txt | grep -E "^(\\d{3}-|\\(\\d{3}\\)\\ )\\d{3}-\\d{4}$"\n```\nIt works in my mac bash shell, but failed for the submission.\nThen I changed my code to below:\n```\ncat file.txt | grep -E "^([0-9]{3}-|\\([0-9]{3}\\)\\ )[0-9]{3}-[0-9]{4}$"\n```\nThen passed...
1
0
[]
1
valid-phone-numbers
why shebang and regular bash script not working?
why-shebang-and-regular-bash-script-not-jn15n
\n#!/bin/bash\ninput = \'file.txt\'\nre=\'([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]\'\nre2=\'[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]\'
erjan
NORMAL
2020-03-18T11:08:22.584823+00:00
2020-03-18T11:08:22.584858+00:00
225
false
```\n#!/bin/bash\ninput = \'file.txt\'\nre=\'([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]\'\nre2=\'[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]\'\nwhile IFS read -r line;\ndo if [[$line = ~ $re || $line = ~re2 ]];\nthen echo $line\n```
1
1
[]
0
valid-phone-numbers
Solution without grep, awk, sed
solution-without-grep-awk-sed-by-kostmet-ncnp
\nwhile read LINE; do if [[ $LINE =~ (^\\([0-9]{3}\\)[[:blank:]][0-9]{3}-[0-9]{4}$)|(^[0-9]{3}-[0-9]{3}-[0-9]{4}$) ]]; then echo $LINE; fi; done < file.txt\n
kostmetallist
NORMAL
2019-11-21T23:54:52.516598+00:00
2019-11-21T23:54:52.516642+00:00
920
false
```\nwhile read LINE; do if [[ $LINE =~ (^\\([0-9]{3}\\)[[:blank:]][0-9]{3}-[0-9]{4}$)|(^[0-9]{3}-[0-9]{3}-[0-9]{4}$) ]]; then echo $LINE; fi; done < file.txt\n```
1
0
[]
0
valid-phone-numbers
Trivial awk solution (probably been posted before)
trivial-awk-solution-probably-been-poste-y70g
\nawk -e \'/^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$/{ print; }\' file.txt;\n
thebel
NORMAL
2019-11-14T23:45:15.447901+00:00
2019-11-14T23:45:15.447952+00:00
321
false
```\nawk -e \'/^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$/{ print; }\' file.txt;\n```
1
0
[]
3
valid-phone-numbers
Time = 0ms beats 100% with Memory = 3.1 MB, simple using Regex Grep
time-0ms-beats-100-with-memory-31-mb-sim-w8wg
\ncat file.txt | grep -E "(^[0-9]{3}-|^\\([0-9]{3}\\)\\s)[0-9]{3}-[0-9]{4}$"\n
terminator1296
NORMAL
2019-10-07T09:49:00.767231+00:00
2019-10-07T09:49:00.767278+00:00
828
false
```\ncat file.txt | grep -E "(^[0-9]{3}-|^\\([0-9]{3}\\)\\s)[0-9]{3}-[0-9]{4}$"\n```
1
0
[]
0
valid-phone-numbers
grep -P solution using conditional regex with explanation
grep-p-solution-using-conditional-regex-6tlnl
Conditional regular expressions are not always the most efficient solution. However, they can be really useful in reducing the length of the regular expression
akpircher
NORMAL
2019-07-09T20:22:49.803994+00:00
2019-07-09T20:22:49.804032+00:00
537
false
Conditional regular expressions are not always the most efficient solution. However, they _can_ be really useful in reducing the length of the regular expression by removing a long "or" statement with repeating elements. This is not one of those cases, but it\'s a fun solution. The downside is that they are harder to read.\n\n```bash\ngrep -xP \'(\\()?\\d{3}(?(1)\\) |-)\\d{3}-\\d{4}\' file.txt\n```\n\n`(\\()?` - capture opening parenthesis at start as group 1, if it exists\n`\\d{3}` - 3 digit area code\n`(?(1)\\) |-)` - If an opening parenthesis was captured as group 1, grab a closing parenthesis followed by a space. Otherwise, look for a dash.\n`\\d{3}-\\d{4}` - get the rest of the number.\n\nThis is effectively equivalent to \n```bash\ngrep -xP \'(\\(\\d{3}\\) |\\d{3}-)\\d{3}-\\d{4}\' file.txt\n```\n
1
0
[]
0
valid-phone-numbers
egrep solution
egrep-solution-by-charliekenney23-ee73
\ncat file.txt | egrep \'^(\\([[:digit:]]{3}\\) |[[:digit:]]{3}-)[[:digit:]]{3}-[[:digit:]]{4}$\'\n
charliekenney23
NORMAL
2019-06-25T05:38:48.434891+00:00
2019-06-25T05:38:48.434936+00:00
471
false
```\ncat file.txt | egrep \'^(\\([[:digit:]]{3}\\) |[[:digit:]]{3}-)[[:digit:]]{3}-[[:digit:]]{4}$\'\n```
1
0
[]
0
valid-phone-numbers
egrep solution
egrep-solution-by-codeywodey-7t05
bash\ncat file.txt | egrep \'^(\\([0-9]{3}\\)\\s{1}|[0-9]{3}-)[0-9]{3}-[0-9]{4}$\'\n
codeywodey
NORMAL
2019-04-14T01:18:40.511719+00:00
2019-04-14T01:18:40.511762+00:00
332
false
```bash\ncat file.txt | egrep \'^(\\([0-9]{3}\\)\\s{1}|[0-9]{3}-)[0-9]{3}-[0-9]{4}$\'\n```
1
0
[]
1
valid-phone-numbers
Fastest Awk Solution [8ms]
fastest-awk-solution-8ms-by-ganbatteimas-ehga
awk\nawk \'{if($0 ~ /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ || $0 ~ /^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$/){printf $0"\\n"}}\' file.txt\n\n\nSimply processes each line and
ganbatteimasu19
NORMAL
2019-03-25T00:50:51.405276+00:00
2019-03-25T00:50:51.405368+00:00
428
false
```awk\nawk \'{if($0 ~ /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ || $0 ~ /^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$/){printf $0"\\n"}}\' file.txt\n```\n\nSimply processes each line and checks if the entire record (default newline separated) has exactly the needed formats specified and prints each line that does.
1
0
[]
0
valid-phone-numbers
Grep
grep-by-cantu_reinhard-0p20
Never use solutions like these. Debugging this would be hell. grep "^\(\([0-9]\{3\}-\)\|\(([0-9]\{3\})\s\)\)[0-9]\{3\}-[0-9]\{4\}$" file.txt
cantu_reinhard
NORMAL
2018-10-16T21:07:42.070900+00:00
2018-10-16T21:07:42.070993+00:00
386
false
Never use solutions like these. Debugging this would be hell. ``` grep "^\(\([0-9]\{3\}-\)\|\(([0-9]\{3\})\s\)\)[0-9]\{3\}-[0-9]\{4\}$" file.txt ```
1
0
[]
0
valid-phone-numbers
Wrong Output of Shell question "valid phone number"
wrong-output-of-shell-question-valid-pho-s0ur
For Shell Question "valid phone number", I submitted the below code: \n\n while read LINE\n do\n if [[ $LINE =~ "^\([0-9]{3}\) [0-9]{3}-[0-9]{4}
bati_goal
NORMAL
2015-04-23T12:58:41+00:00
2015-04-23T12:58:41+00:00
595
false
For Shell Question "valid phone number", I submitted the below code: \n\n while read LINE\n do\n if [[ $LINE =~ "^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$" ]] || [[ $LINE =~ "^[0-9]{3}-[0-9]{3}-[0-9]{4}$" ]]; then\n echo $LINE\n fi\n done < 'file.txt'\n\nFinally, Leetcode judge my code to wrong output by one input "123-456-7891".\nHowever, such input can be pass from my own test.\n\n ytjiang@xxxxx:~/code_practice % sh ValidPhoneNumber.sh\n 123-456-7891\n\nReally wired me....\n\nThanks in advance!
1
0
[]
1
valid-phone-numbers
whereis wrong with my pattern? ask for help
whereis-wrong-with-my-pattern-ask-for-he-2rh6
my grep solution, the code is like:\n\ngrep "\\(?\\d{3}\\)?[- ]\\d{3}-\\d{4}" file.txt\n\nbut when it came across test case "123-456-7891", it didn't print out
lucasdove
NORMAL
2017-05-21T12:30:41.550000+00:00
2017-05-21T12:30:41.550000+00:00
435
false
my grep solution, the code is like:\n```\ngrep "\\(?\\d{3}\\)?[- ]\\d{3}-\\d{4}" file.txt\n```\nbut when it came across test case "123-456-7891", it didn't print out anything. could someone tell me why please?\nYet I put test case "123-456-7891" into a file, and open it with notepad++ on windows, using the same pattern to find matched lines, and it worked! That really makes me confused
1
0
[]
1
valid-phone-numbers
📞 Master Regex Filtering – Unlock the Power of Pattern Matching in Bash!
master-regex-filtering-unlock-the-power-ggz6v
IntuitionWhen processing text files, regular expressions allow us to find lines that match specific patterns. In this case, we're asked to identify phone number
loginov-kirill
NORMAL
2025-04-07T22:12:54.357568+00:00
2025-04-07T22:12:54.357568+00:00
433
false
# Intuition When processing text files, regular expressions allow us to find lines that match specific patterns. In this case, we're asked to identify phone numbers in two formats. # Approach ![image.png](https://assets.leetcode.com/users/images/e6619933-3be7-471b-85ec-2b91edba9e10_1744063971.0943432.png) - Use `grep` with the `-E` flag to enable extended regex. - The regex matches two valid phone number formats: - `(123) 456-7890` - `123-456-7890` - Each part is validated: - 3 digits enclosed in parentheses or followed by a dash. - A space or dash separator. - 3 digits, then a dash, then 4 digits. # Complexity - Time complexity: \(O(n)\), where `n` is the number of lines in the file. - Space complexity: \(O(1)\), uses constant space for pattern matching. # Code ```bash [] grep -E '^((\([0-9]{3}\) [0-9]{3}-[0-9]{4})|([0-9]{3}-[0-9]{3}-[0-9]{4}))$' file.txt ``` <img src="https://assets.leetcode.com/users/images/b91de711-43d7-4838-aabe-07852c019a4d_1743313174.0180438.webp" width="270"/>
0
0
['Shell', 'Bash']
1
valid-phone-numbers
Kian Ilanluo
kian-ilanluo-by-kianilanluo-r3ry
IntuitionJust Think simpleApproach60 ms Beats 84.45%Complexity Time complexity: 60 ms Beats 84.45% Space complexity: 60 ms Beats 84.45% Code
kianilanluo
NORMAL
2025-03-31T14:31:38.792726+00:00
2025-03-31T14:31:38.792726+00:00
2
false
# Intuition Just Think simple # Approach 60 ms Beats 84.45% # Complexity - Time complexity: 60 ms Beats 84.45% - Space complexity: 60 ms Beats 84.45% # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -E '^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\([0-9]{3}\) [0-9]{3}-[0-9]{4} ``` file.txt ```
0
0
['Bash']
0
valid-phone-numbers
shell
shell-by-rohan_shelke-9azd
IntuitionApproachComplexity Time complexity: Space complexity: Code
Rohan_Shelke
NORMAL
2025-03-30T05:27:00.605218+00:00
2025-03-30T05:27:00.605218+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. file="file.txt" regex="^([0-9]{3}-[0-9]{3}-[0-9]{4})$|^(\([0-9]{3}\) [0-9]{3}-[0-9]{4})$" grep -E "$regex" "$file" ```
0
0
['Bash']
0
valid-phone-numbers
❤️ Well explained what is the regex
well-explained-what-is-the-regex-by-muna-ksz9
IntuitionApproachComplexity Time complexity: Space complexity: CodeCode explaingrep Search for text in a file -E Enable extended regex ^ Match start of line $
Munavar_PM
NORMAL
2025-03-28T21:55:14.458720+00:00
2025-03-28T21:55:14.458720+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -E '^(\([0-9]{3}\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4}) ``` file.txt ``` # Code explain grep Search for text in a file -E Enable extended regex ^ Match start of line $ Match end of line ` ` [0-9]{3} Match exactly 3 digits - Match a hyphen (-) \( and \) Match literal parentheses () file.txt Input file
0
0
['Bash']
0
valid-phone-numbers
One liner command
one-liner-command-by-niladridhar1-5jls
IntuitionSimple One liner command to get all the valid phone numbersCode
niladridhar1
NORMAL
2025-03-27T05:04:01.867928+00:00
2025-03-27T05:04:01.867928+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Simple One liner command to get all the valid phone numbers # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. cat file.txt | grep -E '^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\([0-9]{3}\) [0-9]{3}-[0-9]{4} ``` ```
0
0
['Bash']
0
valid-phone-numbers
Solution using grep onliner extended regex
solution-using-grep-onliner-extended-reg-1y6y
Code
Nirzak
NORMAL
2025-03-25T19:50:40.323345+00:00
2025-03-25T19:50:40.323345+00:00
4
false
# Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -E "^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$" file.txt ```
0
0
['Bash']
0
valid-phone-numbers
One-line solution with regex pattern
one-line-solution-with-regex-pattern-by-c2pdq
IntuitionApproach Use regex as pattern for grep Either start with any of these 2 patterns => ^(pattern1|pattern2) pattern1: 3 digits and dash (e.g. 123-) =>
Lesliee_2101
NORMAL
2025-03-21T13:40:09.202350+00:00
2025-03-21T13:41:27.490328+00:00
8
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> - Use regex as pattern for grep - Either start with any of these 2 patterns => ^($$pattern1$$|$$pattern2$$) $$pattern1$$: 3 digits and dash (e.g. 123-) => \d{3}- $$pattern2$$: 3 digits inside paranthesis then space (e.g. (123) ) => \\(\d\d\d\\)\s - Always end with $$pattern3$$: => pattern3$ - $$pattern3$$: 345-2345 => \d{3}-d{4} # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. # start with either \d{3}- or \( \d\d\d \) \s (e.g "987-" or "(987) ") # => ^( \(\d\d\d\)\s | \d{3}- ) # end with \d{3}-\d{4} (e.g. 333-1234) # => \d{3}-\d{4}$ grep -P '^(\(\d\d\d\)\s|\d{3}-)\d{3}-\d{4}$' file.txt ```
0
0
['Bash']
0
valid-phone-numbers
Bash code 100%
bash-code-100-by-sunnat_dev_2011-ycdx
IntuitionApproachComplexity Time complexity: Space complexity: Code
sunnat_dev_2011
NORMAL
2025-03-20T17:55:19.179327+00:00
2025-03-20T17:55:19.179327+00:00
9
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```bash [] grep -E '^(\([0-9]{3}\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4}) ``` file.txt ```
0
0
['Bash']
0
valid-phone-numbers
Simplest approach with explanation of regex and flags
simplest-approach-with-explanation-of-re-7s6v
IntuitionJust use grep command with -E flag for multiple regexApproachpass the regular expressions [] : with - between represents range of selection {} : repres
Abhijit_Dolai
NORMAL
2025-03-19T20:07:21.790181+00:00
2025-03-19T20:07:21.790181+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Just use grep command with -E flag for multiple regex # Approach <!-- Describe your approach to solving the problem. --> pass the regular expressions - [] : with - between represents range of selection - {} : represents no. of times - \ : followed by any character , ignores their special meaning - ^ : starting of line - $ : ending of line make sure to remove useless spaces(any) within the regex string , to pass all testcases. As it is treated as the space is treated as pattern. # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -E '^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$|^\([0-9]{3}\) [0-9]{3}\-[0-9]{4} ``` file.txt ```
0
0
['Bash']
0
valid-phone-numbers
Regex Phonenumbers
regex-phonenumbers-by-mrsander901-s7vo
IntuitionUse regex to filter phone numbers from a file.ApproachUse grep -E with two patterns: xxx-xxx-xxxx or (xxx) xxx-xxxx, anchored to match full lines.Code
MrSander901
NORMAL
2025-03-09T15:37:10.973276+00:00
2025-03-09T15:37:10.973276+00:00
9
false
# Intuition Use regex to filter phone numbers from a file. # Approach Use grep -E with two patterns: xxx-xxx-xxxx or (xxx) xxx-xxxx, anchored to match full lines. # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -E '^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^\([0-9]{3}\) [0-9]{3}-[0-9]{4} ``` file.txt ```
0
0
['Bash']
0
valid-phone-numbers
193. Valid Phone Numbers Solution
193-valid-phone-numbers-solution-by-muha-quch
IntuitionThe problem requires extracting phone numbers that match two specific formats: (xxx) xxx-xxxx (where x is a digit) xxx-xxx-xxxx Given that the input is
Muhammad_Haris_Ahsan
NORMAL
2025-03-06T02:42:41.210800+00:00
2025-03-06T02:42:41.210800+00:00
12
false
# Intuition The problem requires extracting phone numbers that match two specific formats: 1. `(xxx) xxx-xxxx` (where `x` is a digit) 2. `xxx-xxx-xxxx` Given that the input is a text file where each line contains a single phone number, we can efficiently solve this using `grep`, a command-line tool that supports regular expressions for pattern matching. # Approach We use `grep -E` (extended regex) to match the required phone number formats: - **Pattern 1:** `^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$` - Ensures the format `(xxx) xxx-xxxx` with exactly three digits inside parentheses, a space, and then three digits followed by a hyphen and four digits. <br> <br> - **Pattern 2:** `^[0-9]{3}-[0-9]{3}-[0-9]{4}$` - Ensures the format `xxx-xxx-xxxx`, where each part is exactly three, three, and four digits separated by hyphens. We use `grep -E` (extended regex) with the `|` (OR) operator to match either format. # Complexity - **Time complexity**: $$O(n)$$, where `n` is the number of lines in the file. `grep` processes each line once and applies the regex check in constant time. - **Space complexity**: $$O(1)$$, as `grep` does not use additional memory proportional to the input size. # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -E '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4} ``` file.txt ```
0
0
['Bash']
0
valid-phone-numbers
Concise Shell Script for Valid Phone Number Extraction using grep
concise-shell-script-for-valid-phone-num-dbev
IntuitionUse grep to filter lines in file.txt that match the specified phone number formats.ApproachUse grep -E with a regular expression to match either (xxx)
sharipovikromjon
NORMAL
2025-03-01T01:50:04.140774+00:00
2025-03-01T01:50:04.140774+00:00
7
false
# Intuition Use **grep** to filter lines in **file.txt** that match the specified phone number formats. # Approach Use **grep -E** with a regular expression to match either **(xxx) xxx-xxxx** or **xxx-xxx-xxxx** formats. Anchor the regex to the start (**^**) and end (**$**) of the line for exact matches. Use **\s** for whitespace and **[0-9]{3}**, **[0-9]{4}** for digit patterns. Output only matching lines with **o** (optional). # Complexity - Time complexity: $$O(n)$$ linear scan of the file. - Space complexity: $$O(1)$$ constant memory usage.**Bold** # Code ```bash [] grep -E -o '^(\([0-9]{3}\)\s[0-9]{3}-[0-9]{4})$|^([0-9]{3}-[0-9]{3}-[0-9]{4})$' file.txt ```
0
0
['Bash']
0
valid-phone-numbers
193. Valid Phone Numbers
193-valid-phone-numbers-by-1hbxnllboo-odf8
IntuitionUse regex to match valid phone numbers.ApproachUsing grep is enough to perform the regex match.Code
1hBxNLlbOO
NORMAL
2025-02-16T05:42:16.589322+00:00
2025-02-16T05:42:16.589322+00:00
9
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Use regex to match valid phone numbers. # Approach <!-- Describe your approach to solving the problem. --> Using `grep` is enough to perform the regex match. # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -E "^(([0-9]{3}-)|(\([0-9]{3}\)\s))[0-9]{3}-[0-9]{4}$" file.txt ```
0
0
['Bash']
0
valid-phone-numbers
No brainer, one liner
no-brainer-one-liner-by-nishant_sheoran-nhmr
Code
nishant_sheoran
NORMAL
2025-02-14T12:44:15.040346+00:00
2025-02-14T12:44:15.040346+00:00
20
false
# Code ```bash [] grep -e "^[0-9]\{3\}\-[0-9]\{3\}\-[0-9]\{4\}$" -e "^([0-9]\{3\}) [0-9]\{3\}\-[0-9]\{4\}$" file.txt ```
0
0
['Shell', 'Bash']
0
valid-phone-numbers
Valid Phone Number using GREP
valid-phone-number-using-grep-by-samahaa-7w9u
IntuitionThe problem requires us to extract valid phone numbers from a file. A valid phone number follows one of two formats:(xxx) xxx-xxxx xxx-xxx-xxxx Given t
samahaabbas
NORMAL
2025-02-09T11:49:03.900646+00:00
2025-02-09T11:49:03.900646+00:00
14
false
# Intuition The problem requires us to extract valid phone numbers from a file. A valid phone number follows one of two formats: (xxx) xxx-xxxx xxx-xxx-xxxx Given that each line contains only one phone number, a line-by-line pattern match is the best approach. # Approach We use grep with extended regular expressions (-E) to match the valid phone number formats: (^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$) → Matches (xxx) xxx-xxxx format (^[0-9]{3}-[0-9]{3}-[0-9]{4}$) → Matches xxx-xxx-xxxx format We also use LC_ALL=C to speed up execution by disabling locale processing. # Complexity - Time complexity: Best case: O(1) (file is empty) Average case: O(n) (each line is checked once) Worst case: O(n) (all lines match) - Space complexity: O(1), since grep operates in a streaming fashion without extra memory usage. # Code ```bash [] LC_ALL=C grep -E '^(\([0-9]{3}\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4}) ``` file.txt ```
0
0
['Bash']
0
valid-phone-numbers
Solution using grep+regex
solution-using-grepregex-by-u0ejuzk0o7-0ks8
IntuitionThe problem asks us to identify valid phone numbers from a file. We are given specific formats that a valid phone number must follow: (xxx) xxx-xxxx xx
mehraj_hossain
NORMAL
2025-02-09T02:35:01.509985+00:00
2025-02-09T02:35:01.509985+00:00
12
false
# Intuition The problem asks us to identify valid phone numbers from a file. We are given specific formats that a valid phone number must follow: - `(xxx) xxx-xxxx` - `xxx-xxx-xxxx` Since both formats are well-structured, regular expressions (regex) can easily be used to capture and validate these patterns. We can use the `grep` command in bash with an extended regular expression to filter valid phone numbers from the file. # Approach use grep with regex # Complexity - Time complexity: $$O(n)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:$$O(1)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -E '^(\([0-9]{3}\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4}) ``` file.txt ```
0
0
['Bash']
0
valid-phone-numbers
Valid Phone Numbers - Solution
valid-phone-numbers-solution-by-4auz20ig-cx9v
IntuitionThe problem requires extracting and printing phone numbers that match a specific format from a text file. Since each line contains a single phone numbe
4AUZ20iGg6
NORMAL
2025-02-08T22:02:03.666894+00:00
2025-02-08T22:02:03.666894+00:00
7
false
# Intuition The problem requires extracting and printing phone numbers that match a specific format from a text file. Since each line contains a single phone number, we need a method to validate each line against the given formats: 1. ```(xxx) xxx-xxxx``` (Parentheses and space included) 1. ```xxx-xxx-xxxx``` (Only dashes) Regular expressions (```regex```) are good for this task because they can match structured patterns. We can use ```grep```, a command-line tool that supports regex, to filter and print valid lines. # Approach 1. We use ```grep -E``` (extended regex) to match the two possible formats and filter out invalid lines. The approach follows these steps: - Matches exactly 10 digits, formatted in one of the two ways. - Ensures correct placement of parentheses, spaces, and dashes. - Ensures that the entire line conforms to the pattern (using ```^``` and ```$```). 2. The regex pattern: ```regex [] ^(\([0-9]{3}\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4})$ ``` - ```\([0-9]{3}\) [0-9]{3}-[0-9]{4}``` → Matches (xxx) xxx-xxxx - ```[0-9]{3}-[0-9]{3}-[0-9]{4}``` → Matches xxx-xxx-xxxx - ```|``` → Acts as an OR between the two formats - ```^...$``` → Ensures the entire line matches exactly one of the patterns 3. Run the following command in Bash: ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -E "^(\([0-9]{3}\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4})$" file.txt ``` # Complexity - Time complexity: - ```grep``` processes each line once, performing a regex match. - Let n be the number of lines in ```file.txt```. Since regex matching takes O(1) per line, the overall complexity is: O(n) - Space complexity: - ```grep``` operates in a streaming fashion, without storing the entire file in memory. - The output buffer may store valid phone numbers but does not scale with input size. - Therefore, space complexity is: O(1) # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -E "^(\([0-9]{3}\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4})$" file.txt ```
0
0
['Bash']
0
valid-phone-numbers
Valid Phone Number
valid-phone-number-by-suman_tandan-6xjs
IntuitionApproachComplexity Time complexity: Space complexity: Code
suman_tandan
NORMAL
2025-02-05T05:30:25.108829+00:00
2025-02-05T05:30:25.108829+00:00
12
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. grep -E '^(\([0-9]{3}\) [0-9]{3}-[0-9]{4}|[0-9]{3}-[0-9]{3}-[0-9]{4}) ``` file.txt ```
0
0
['Bash']
0
valid-phone-numbers
Bash | Validate Phone Numbers Using grep
bash-validate-phone-numbers-using-grep-b-tyx5
IntuitionWe need to extract valid phone numbers from file.txt. A valid phone number follows one of these two formats: xxx-xxx-xxxx (xxx) xxx-xxxx Since we are w
SamuelBrhaneAlemayohu
NORMAL
2025-02-03T17:40:00.176296+00:00
2025-02-03T17:40:00.176296+00:00
32
false
# Intuition We need to extract valid phone numbers from `file.txt`. A **valid phone number** follows one of these two formats: 1. `xxx-xxx-xxxx` 2. `(xxx) xxx-xxxx` Since we are working in **Bash**, we can use `grep` with **regular expressions** to filter out invalid numbers. # Approach 1. **Use `grep -E` (Extended Regex) for pattern matching**: - `^([0-9]{3}-[0-9]{3}-[0-9]{4})$` → Matches **`xxx-xxx-xxxx`** format. - `^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$` → Matches **`(xxx) xxx-xxxx`** format. - **Use `|` (OR operator) to match either pattern**. 2. **Edge Cases Handled**: - **Whitespace handling**: Each line is checked from start (`^`) to end (`$`). - **Invalid formats rejected**: Numbers like `123 456 7890` will be ignored. # Complexity - **Time Complexity**: O(n) - Each line in `file.txt` is scanned once. - **Space Complexity**: O(1) - No extra space is used, only direct processing. # Code ```bash # Read from the file file.txt and output all valid phone numbers to stdout. grep -E "^([0-9]{3}-[0-9]{3}-[0-9]{4}|\([0-9]{3}\) [0-9]{3}-[0-9]{4})$" file.txt
0
0
['Bash']
0
valid-phone-numbers
193. Valid Phone Numbers
193-valid-phone-numbers-by-g8xd0qpqty-s1zv
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-10T07:21:01.725681+00:00
2025-01-10T07:21:01.725681+00:00
24
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```bash [] grep -E '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4} ``` file.txt ```
0
0
['Bash']
0
valid-phone-numbers
POSIX Regexps
posix-regexps-by-spektrokalter-7u2l
null
spektrokalter
NORMAL
2025-01-09T09:04:05.393848+00:00
2025-01-09T09:04:05.393848+00:00
14
false
```txt cat file.txt |grep '^\(([0-9][0-9][0-9]) \|[0-9][0-9][0-9]-\)[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9] ``` ```
0
0
['Bash']
0
valid-phone-numbers
Sonakshi Tiwari
sonakshi-tiwari-by-sonakshigtiwari-ep9k
IntuitionApproachComplexity Time complexity: Space complexity: Code
SONAKSHIGTIWARI
NORMAL
2025-01-07T13:40:19.957434+00:00
2025-01-07T13:40:19.957434+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```bash [] # Read from the file file.txt and output all valid phone numbers to stdout. # Read from the file file.txt and output all valid phone numbers to stdout. grep '^\([0-9]\{3\}-\|([0-9]\{3\}) \)[0-9]\{3\}-[0-9]\{4\} ``` file.txt ```
0
0
['Bash']
0
binary-tree-zigzag-level-order-traversal
[c++] 5ms version: one queue and without reverse operation by using size of each level
c-5ms-version-one-queue-and-without-reve-8msj
\nAssuming after traversing the 1st level, nodes in queue are {9, 20, 8}, And we are going to traverse 2nd level, which is even line and should print value from
stevencooks
NORMAL
2015-03-13T20:50:25+00:00
2018-10-19T14:45:07.857245+00:00
80,421
false
\nAssuming after traversing the 1st level, nodes in queue are {9, 20, 8}, And we are going to traverse 2nd level, which is even line and should print value from right to left [8, 20, 9]. \n\nWe know there are 3 nodes in current queue, so the vector for this level in final result should be of size 3. \nThen, queue [i] -> goes to -> vector[queue.size() - 1 - i]\ni.e. the ith node in current queue should be placed in (queue.size() - 1 - i) position in vector for that line.\n \nFor example, for node(9), it's index in queue is 0, so its index in vector should be (3-1-0) = 2. \n\n\n vector<vector<int> > zigzagLevelOrder(TreeNode* root) {\n if (root == NULL) {\n return vector<vector<int> > ();\n }\n vector<vector<int> > result;\n \n queue<TreeNode*> nodesQueue;\n nodesQueue.push(root);\n bool leftToRight = true;\n \n while ( !nodesQueue.empty()) {\n int size = nodesQueue.size();\n vector<int> row(size);\n for (int i = 0; i < size; i++) {\n TreeNode* node = nodesQueue.front();\n nodesQueue.pop();\n\n // find position to fill node's value\n int index = (leftToRight) ? i : (size - 1 - i);\n\n row[index] = node->val;\n if (node->left) {\n nodesQueue.push(node->left);\n }\n if (node->right) {\n nodesQueue.push(node->right);\n }\n }\n // after this level\n leftToRight = !leftToRight;\n result.push_back(row);\n }\n return result;\n }
503
8
['C++']
47
binary-tree-zigzag-level-order-traversal
My accepted JAVA solution
my-accepted-java-solution-by-awaylu-dnra
public class Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) \n {\n List<List<Integer>> sol = new ArrayList<>()
awaylu
NORMAL
2014-09-17T06:17:28+00:00
2018-10-20T04:13:36.538433+00:00
145,645
false
public class Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) \n {\n List<List<Integer>> sol = new ArrayList<>();\n travel(root, sol, 0);\n return sol;\n }\n \n private void travel(TreeNode curr, List<List<Integer>> sol, int level)\n {\n if(curr == null) return;\n \n if(sol.size() <= level)\n {\n List<Integer> newLevel = new LinkedList<>();\n sol.add(newLevel);\n }\n \n List<Integer> collection = sol.get(level);\n if(level % 2 == 0) collection.add(curr.val);\n else collection.add(0, curr.val);\n \n travel(curr.left, sol, level + 1);\n travel(curr.right, sol, level + 1);\n }\n }\n\n1. O(n) solution by using LinkedList along with ArrayList. So insertion in the inner list and outer list are both O(1),\n2. Using DFS and creating new lists when needed.\n\nshould be quite straightforward. any better answer?
476
7
['Java']
87
binary-tree-zigzag-level-order-traversal
JAVA Double Stack Solution
java-double-stack-solution-by-tjcd-uqg2
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n TreeNode c=root;\n List<List<Integer>> ans =new ArrayList<List<Integer>>();\n i
tjcd
NORMAL
2015-12-26T14:24:44+00:00
2018-10-26T19:00:53.166043+00:00
30,507
false
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n TreeNode c=root;\n List<List<Integer>> ans =new ArrayList<List<Integer>>();\n if(c==null) return ans;\n Stack<TreeNode> s1=new Stack<TreeNode>();\n Stack<TreeNode> s2=new Stack<TreeNode>();\n s1.push(root);\n while(!s1.isEmpty()||!s2.isEmpty())\n {\n List<Integer> tmp=new ArrayList<Integer>();\n while(!s1.isEmpty())\n {\n c=s1.pop();\n tmp.add(c.val);\n if(c.left!=null) s2.push(c.left);\n if(c.right!=null) s2.push(c.right);\n }\n ans.add(tmp);\n tmp=new ArrayList<Integer>();\n while(!s2.isEmpty())\n {\n c=s2.pop();\n tmp.add(c.val);\n if(c.right!=null)s1.push(c.right);\n if(c.left!=null)s1.push(c.left);\n }\n if(!tmp.isEmpty()) ans.add(tmp);\n }\n return ans;\n }
336
4
['Java']
29
binary-tree-zigzag-level-order-traversal
[c++] Easy to understand, one approach to solve Zigzag & Level order traversal
c-easy-to-understand-one-approach-to-sol-0vig
This approch can be used to solve both level order traversal & zig zag traversal.\nIt\'s easy to start with the level order traversal. I hope the comments are c
mnumtw7
NORMAL
2018-09-26T15:49:46.925697+00:00
2019-08-17T23:52:56.083858+00:00
22,383
false
This approch can be used to solve both level order traversal & zig zag traversal.\nIt\'s easy to start with the level order traversal. I hope the comments are clear.\n\n```\nvector<vector<int>> levelOrder(TreeNode* root) {\n if (!root) return {}; // return if root is null\n queue<TreeNode*> q;\n q.push(root); //push the root node.\n vector<vector<int>> out; //result vector\n \n\t\t /*\n\t\t * Idea is to create a vector for every level based on the queue size.\n\t\t * eg: if a level has four elements say 1, 2, 3, 4 -> Then create a vector of size 4.\n\t\t * \n\t\t * note: size of the queue is computed before the loop, so that we don\'t consider \n\t\t * newly pushed elements.\n\t\t */\n\t\t \n while (!q.empty()) {\n \n int sz = q.size(); /* current queue size */\n vector<int> curr(sz); /* vector of size sz */\n\t\t\t\t\t\t\n for (int i = 0; i < sz; i++) {\n TreeNode* tmp = q.front();\n q.pop();\n curr[i] = tmp->val; /* insert to the correct index */\n\t\t\t\t\n\t\t\t\t/* Add the left & right nodes to the queue in the loop. */\n if (tmp->left) q.push(tmp->left);\n if (tmp->right) q.push(tmp->right);\n }\n out.push_back(curr); /* once the level is done, push the vector to output vector. */\n }\n return out;\n }\n```\n\nThe same idea can be extended to zig-zag traversal. The only difference would be, if we are on an even level (say second level)** insert into the vector from end. Odd levels insert from beginning.**\n```\n\nvector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n \n if (!root) return {};\n \n queue<TreeNode*> q;\n vector<vector<int>> out;\n \n q.push(root); \n int level = 0; /* to alternate levels, or a bool variable */\n \n while (!q.empty()) {\n \n int sz = q.size(); \n vector<int> curr(sz); \n \n for (int i = 0; i < sz; i++) {\n \n TreeNode* tmp = q.front();\n q.pop();\n \n if (level == 0) {\n curr[i] = tmp->val; // odd level, insert like 0, 1, 2, 3 etc. \n } else {\n curr[sz - i - 1] = tmp->val; /* even level insert from end. 3, 2, 1, 0. (sz - i - 1) to get the index from end */\n }\n \n if (tmp->left) q.push(tmp->left);\n if (tmp->right) q.push(tmp->right);\n }\n out.push_back(curr); // now push the level traversed to output vector\n level = !level; // toggle the level using negation. or level == 0 ? level = 1 : level = 0;\n }\n return out;\n```\n\nThank you for reading. Please let me your comments/feedback.
241
3
['Tree', 'C']
19
binary-tree-zigzag-level-order-traversal
[Python] Clean BFS solution, explained
python-clean-bfs-solution-explained-by-d-eudl
In this problem we need to traverse binary tree level by level. When we see levels in binary tree, we need to think about bfs, because it is its logic: it first
dbabichev
NORMAL
2020-07-22T10:47:30.078047+00:00
2020-07-22T10:47:30.078100+00:00
19,826
false
In this problem we need to traverse binary tree level by level. When we see levels in binary tree, we need to think about **bfs**, because it is its logic: it first traverse all neighbors, before we go deeper. Here we also need to change direction on each level as well. So, algorithm is the following:\n\n1. We create **queue**, where we first put our root.\n2. `result` is to keep final result and `direction`, equal to `1` or `-1` is direction of traverse.\n3. Then we start to traverse level by level: if we have `k` elements in queue currently, we remove them all and put their children instead. We continue to do this until our queue is empty. Meanwile we form `level` list and then add it to `result`, using correct direction and change direction after.\n\n**Complexity**: time complexity is `O(n)`, where `n` is number of nodes in our binary tree. Space complexity is also `O(n)`, because our `result` has this size in the end. If we do not count output as additional space, then it will be `O(w)`, where `w` is width of tree. It can be reduces to `O(1)` I think if we traverse levels in different order directly, but it is just not worth it.\n\n```\nclass Solution:\n def zigzagLevelOrder(self, root):\n if not root: return []\n queue = deque([root])\n result, direction = [], 1\n \n while queue:\n level = []\n for i in range(len(queue)):\n node = queue.popleft()\n level.append(node.val)\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n result.append(level[::direction])\n direction *= (-1)\n return result\n```\n\nIf you have any questoins, feel free to ask. If you like the solution and explanation, please **upvote!**
237
5
['Breadth-First Search']
23
binary-tree-zigzag-level-order-traversal
A concise and easy understanding Java solution
a-concise-and-easy-understanding-java-so-p03m
public class Solution {\n public List> zigzagLevelOrder(TreeNode root) {\n List> res = new ArrayList<>();\n if(root == null) return res;\n\n
graceluli
NORMAL
2015-11-11T23:29:46+00:00
2018-10-10T02:00:58.630632+00:00
36,436
false
public class Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> res = new ArrayList<>();\n if(root == null) return res;\n\n Queue<TreeNode> q = new LinkedList<>();\n q.add(root);\n boolean order = true;\n int size = 1;\n\n while(!q.isEmpty()) {\n List<Integer> tmp = new ArrayList<>();\n for(int i = 0; i < size; ++i) {\n TreeNode n = q.poll();\n if(order) {\n tmp.add(n.val);\n } else {\n tmp.add(0, n.val);\n }\n if(n.left != null) q.add(n.left);\n if(n.right != null) q.add(n.right);\n }\n res.add(tmp);\n size = q.size();\n order = order ? false : true;\n }\n return res;\n }\n}
140
4
[]
23
binary-tree-zigzag-level-order-traversal
Python simple BFS
python-simple-bfs-by-fangkunjnsy-ynaq
Simple straightforward solution using flag to decide whether from left to right or from right to left\n\n class Solution(object):\n def zigzagLevelOrder(s
fangkunjnsy
NORMAL
2015-09-23T04:24:02+00:00
2018-10-06T11:09:10.913549+00:00
30,587
false
Simple straightforward solution using flag to decide whether from left to right or from right to left\n\n class Solution(object):\n def zigzagLevelOrder(self, root):\n """\n :type root: TreeNode\n :rtype: List[List[int]]\n """\n if not root: return []\n res, temp, stack, flag=[], [], [root], 1\n while stack:\n for i in xrange(len(stack)):\n node=stack.pop(0)\n temp+=[node.val]\n if node.left: stack+=[node.left]\n if node.right: stack+=[node.right]\n res+=[temp[::flag]]\n temp=[]\n flag*=-1\n return res
105
17
[]
31
binary-tree-zigzag-level-order-traversal
Clear iterative solution with deque, no reverse
clear-iterative-solution-with-deque-no-r-rtvl
for zig, pop_back, push_front, left then right, \n\n for zag, pop_front, push_back, right then left\n\n vector> zigzagLevelOrder(TreeNode* root) {\n v
qeatzy
NORMAL
2015-08-09T08:33:26+00:00
2018-10-04T05:20:36.521379+00:00
16,834
false
for zig, pop_back, push_front, left then right, \n\n for zag, pop_front, push_back, right then left\n\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> res;\n if(!root) return res;\n std::deque<TreeNode*> deq;\n deq.push_back(root);\n int iszig=1;\n while(!deq.empty()) {\n int sz=deq.size();\n iszig=iszig^1;\n vector<int> row;\n while(sz--) {\n if(iszig) { // pop_front, push_back, right then left\n root=deq.front();deq.pop_front();\n row.push_back(root->val);\n if(root->right) deq.push_back(root->right);\n if(root->left) deq.push_back(root->left);\n }\n else { // pop_back, push_front, left then right\n root=deq.back();deq.pop_back();\n row.push_back(root->val);\n if(root->left) deq.push_front(root->left);\n if(root->right) deq.push_front(root->right);\n }\n }\n res.push_back(row);\n }\n return res;\n }
78
0
[]
6
binary-tree-zigzag-level-order-traversal
Four python solutions
four-python-solutions-by-nth-attempt-5r7m
Approach - 1\nUsing single ended queue and reverse. Although we are using deque we are utilizing only single ended queue functionality here.\npython\ndef zigzag
nth-attempt
NORMAL
2020-07-23T02:20:54.455285+00:00
2021-02-28T16:28:49.579547+00:00
10,222
false
#### Approach - 1\nUsing single ended queue and reverse. Although we are using `deque` we are utilizing only single ended queue functionality here.\n```python\ndef zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n\tif not root: return []\n\tqueue = collections.deque([root])\n\tres = []\n\teven_level = False\n\twhile queue:\n\t\tn = len(queue)\n\t\tlevel = []\n\t\tfor _ in range(n):\n\t\t\tnode = queue.popleft()\n\t\t\tlevel.append(node.val)\n\t\t\tif node.left:\n\t\t\t\tqueue.append(node.left)\n\t\t\tif node.right:\n\t\t\t\tqueue.append(node.right)\n\t\tif even_level:\n\t\t\tres.append(level[::-1])\n\t\telse:\n\t\t\tres.append(level)\n\t\teven_level = not even_level\n\treturn res\n```\n\n#### Appraoch - 2\nUsing single ended queue and initializing array instead of reversing. \n```python\ndef zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n\tif not root: return []\n\tqueue = collections.deque([root])\n\tres = []\n\teven_level = False\n\twhile queue:\n\t\tn = len(queue)\n\t\tlevel = [0] * n # initalize the array since we know the length\n\t\tfor i in range(n):\n\t\t\tnode = queue.popleft()\n\t\t\tif node.left:\n\t\t\t\tqueue.append(node.left)\n\t\t\tif node.right:\n\t\t\t\tqueue.append(node.right)\n\t\t\tif even_level:\n\t\t\t\tlevel[n-1-i] = node.val\n\t\t\telse:\n\t\t\t\tlevel[i] = node.val\n\t\tres.append(level)\n\t\teven_level = not even_level\n\n\treturn res\n```\n#### Approach - 3\nUsing the double ended queue functionality. We pop from left in odd levels and pop from right in even levels. Trick is to flip the order of left and right when we are appending from left. \n```python\ndef zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n\tif not root: return []\n\tqueue = collections.deque([root])\n\tres = []\n\teven_level = False\n\twhile queue:\n\t\tn = len(queue)\n\t\tlevel = []\n\t\tfor i in range(n):\n\t\t\tif even_level:\n\t\t\t\t# pop from right and append from left.\n\t\t\t\tnode = queue.pop()\n\t\t\t\t# to maintain the order of nodes in the format of [left, right, left, right] \n\t\t\t\t# we push right first since we are appending from left\n\t\t\t\tif node.right: queue.appendleft(node.right)\n\t\t\t\tif node.left: queue.appendleft(node.left)\n\t\t\telse:\n\t\t\t\t# pop from left and append from right\n\t\t\t\tnode = queue.popleft()\n\t\t\t\t# here the order is maintained in the format [left, right, left, right] \n\t\t\t\tif node.left: queue.append(node.left)\n\t\t\t\tif node.right: queue.append(node.right)\n\t\t\tlevel.append(node.val)\n\t\tres.append(level)\n\t\teven_level = not even_level\n\treturn res\n```\n\n#### Approach - 4\nUsing deque for each level instead of list.\n```python\ndef zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root: return []\n res = []\n queue = collections.deque([root])\n even_level = False\n while queue:\n n = len(queue)\n level = collections.deque()\n for _ in range(n):\n node = queue.popleft()\n if even_level:\n level.appendleft(node.val)\n else:\n level.append(node.val)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n res.append(list(level))\n even_level = not even_level\n return res\n```
74
0
['Queue', 'Python', 'Python3']
8
binary-tree-zigzag-level-order-traversal
8-liner Python
8-liner-python-by-tlhuang-w8ga
\nclass Solution(object):\n def zigzagLevelOrder(self, root):\n """\n :type root: TreeNode\n :rtype: List[List[int]]\n """\n
tlhuang
NORMAL
2016-09-05T21:35:46.279000+00:00
2018-10-22T20:47:37.147954+00:00
10,575
false
```\nclass Solution(object):\n def zigzagLevelOrder(self, root):\n """\n :type root: TreeNode\n :rtype: List[List[int]]\n """\n if not root:\n return []\n res, level, direction = [], [root], 1\n while level:\n res.append([n.val for n in level][::direction])\n direction *= -1\n level = [kid for node in level for kid in (node.left, node.right) if kid]\n return res\n```
74
3
[]
11
binary-tree-zigzag-level-order-traversal
Two simple approaches : O(n)
two-simple-approaches-on-by-thisisakshat-7jyo
1.)Recursion: After doing level order traversal using recursion, we simply reverse the vectors at alternate levels\n\nclass Solution {\npublic:\n void helper
thisisakshat
NORMAL
2021-03-17T06:52:27.482277+00:00
2021-03-17T06:52:27.482313+00:00
7,761
false
**1.)Recursion:** After doing level order traversal using recursion, we simply reverse the vectors at alternate levels\n```\nclass Solution {\npublic:\n void helper(TreeNode*root,vector<vector<int>>&res,int level)\n {\n if(!root) return; \n if(level>=res.size())\n res.push_back({});\n res[level].push_back(root->val);\n helper(root->left,res,level+1);\n helper(root->right,res,level+1);\n }\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>>res;\n if(!root) return res;\n helper(root,res,0); \n for(int i=1;i<res.size();i=i+2)\n {\n reverse(res[i].begin(),res[i].end());\n }\n return res;\n }\n};\n```\n*Runtime:0ms\nSpace: O(n) for res vector\nTime:O(n)*\n\n**2.)Using queue(BFS):**\n```\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>>res;\n if(!root) return res;\n vector<int>row;\n queue<TreeNode*>q;\n int x=0;\n q.push(root);\n while(!q.empty())\n {\n int size=q.size();\n for(int i=0;i<size;i++)\n {\n TreeNode*root=q.front();\n q.pop();\n row.push_back(root->val);\n if(root->left!=NULL)\n q.push(root->left);\n if(root->right!=NULL)\n q.push(root->right);\n }\n if(x%2==0)\n res.push_back(row);\n else\n {\n reverse(row.begin(),row.end());\n res.push_back(row);\n }\n row.clear();\n x+=1;\n }\n return res;\n }\n};\n```\n*Runtime:0ms\nSpace:O(n)\nTime:O(n)*\n\nI hope this helped!!\nIf you like, please **UPVOTE**\'\nHappy Coding :)
61
3
['Stack', 'Depth-First Search', 'Breadth-First Search', 'Recursion', 'Queue', 'C', 'C++']
8
binary-tree-zigzag-level-order-traversal
C++| Level Order Traversal | Beats 100% | BFS
c-level-order-traversal-beats-100-bfs-by-7lg3
Intuition\n Describe your first thoughts on how to solve this problem. \nSo Do Simple Level order but alternately revrse the elemnts of level.\n- Either we can
Xahoor72
NORMAL
2023-02-17T17:44:03.017809+00:00
2023-02-17T17:44:03.017992+00:00
10,120
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSo Do Simple Level order but alternately revrse the elemnts of level.\n- Either we can reverse the vector storing the elemnts f that level\n- Or we just insert from last index so that it will be in reverse order itself.(More Efficient)\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Level Order Traversal: For More Understanding [Refer Here](https://leetcode.com/problems/binary-tree-level-order-traversal/solutions/3196962/c-bfs-dfs-on-explained/)\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n**Level Order Traversal by Reversing vector alternately**\n```\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>>ans;\n if(!root)return ans;\n queue<TreeNode*>q;\n q.push(root);\n int i=0;\n while(!q.empty()){\n int sz=q.size();\n vector<int>v;\n while(sz--){\n TreeNode * f=q.front();\n v.push_back(q.front()->val);\n q.pop();\n if(f->left)q.push(f->left);\n if(f->right)q.push(f->right);\n\n }\n if(i++%2)\n reverse(v.begin(),v.end());\n ans.push_back(v);\n\n }\n return ans;\n \n }\n};\n```\n**More Optimized Level Order Wihtout Reversing Vector**\n```\nvector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>>ans;\n if(!root)return ans;\n queue<TreeNode*>q;\n q.push(root);\n int i=0;\n while(!q.empty()){\n int sz=q.size();\n vector<int>v(sz);\n int j=0,n=sz;\n while(sz--){\n TreeNode * f=q.front();\n q.pop();\n if(i%2==0)\n v[j]=f->val;\n else v[n-j-1]=f->val;\n j++;\n if(f->left)q.push(f->left);\n if(f->right)q.push(f->right);\n }\n i++;\n ans.push_back(v);\n\n }\n return ans;\n \n }\n```\n# Upvote If Help full
50
3
['Tree', 'Depth-First Search', 'Breadth-First Search', 'Binary Tree', 'C++']
2
binary-tree-zigzag-level-order-traversal
🚀Simplest Solution🚀||🔥Full Explanation||🔥C++🔥|| Python3
simplest-solutionfull-explanationc-pytho-9e87
Consider\uD83D\uDC4D\n\n Please Upvote If You Find It Helpful\n\n# Intuition\nIntuition of this problem is very simple.\nWe use the Level Ord
naman_ag
NORMAL
2023-02-19T01:36:46.001514+00:00
2023-02-19T04:20:26.419287+00:00
7,726
false
# Consider\uD83D\uDC4D\n```\n Please Upvote If You Find It Helpful\n```\n# Intuition\nIntuition of this problem is very simple.\nWe use the **Level Order Traversal** of Binary tree.\nFor the Zig Zag Movement we are using a variable `level` when it is **zero** we **move from Left to Right** and when it is `one` we move from **Right to Left**.\nFor Level order traversal I am using a **Queue**.\nInitially we push `root` element in the queue. Traverse all elements of the tree.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach : BFS, Level Order Traversal\n Example : `root` = [3,9,20,null,null,15,7]\n\n Initially `queue` = [3], level = 0\n In first pass\n size = 1 `queue` = [3]\n `curr[0]` = 3\n We push 3->left and 3->right in queue\n `queue` = [9, 20]\n So our loop only run 1 time beacuase size is 1.\n\n Now we push curr to `output` vector `output` = [[3]]\n Now `level` = 1\n\n In Second pass\n size = 2 `queue` = [9, 20]\n `curr[1]` = 20\n `curr[0]` = 9\n We push 20->left and 20->right in queue\n `queue` = [15, 7]\n And 9->left = NULL , 9->right = NULL so we do not push it.\n So our loop run 2 times beacuase size is 2.\n\n Now we push curr to `output` vector `output` = [[3], [20, 9]]\n Now `level` = 0\n\n In this way me iterate for the 15 and 7.\n So answer is `[[3], [20, 9], [15, 7]]`\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(W) width of the tree\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n \n if (!root) return {};\n \n queue<TreeNode*> q;\n vector<vector<int>> out;\n \n q.push(root); \n int level = 0; /* to alternate levels, or a bool variable */\n \n while (!q.empty()) {\n \n int sz = q.size(); \n vector<int> curr(sz); \n \n for (int i = 0; i < sz; i++) {\n \n TreeNode* tmp = q.front();\n q.pop();\n \n if (level == 0) {\n curr[i] = tmp->val; // odd level, insert like 0, 1, 2, 3 etc. \n } else {\n curr[sz - i - 1] = tmp->val; /* even level insert from end. 3, 2, 1, 0. (sz - i - 1) to get the index from end */\n }\n \n if (tmp->left) q.push(tmp->left);\n if (tmp->right) q.push(tmp->right);\n }\n out.push_back(curr); // now push the level traversed to output vector\n level = !level; // toggle the level using negation. or level == 0 ? level = 1 : level = 0;\n }\n return out;\n }\n};\n\n```\n```python []\nfrom queue import Queue\nclass Solution:\n def zigzagLevelOrder(self, A: TreeNode) -> List[List[int]]:\n if not A:\n return []\n queue = Queue()\n queue.put(A)\n output = []\n curr = []\n level = 0\n while not queue.empty():\n size = queue.qsize()\n curr = []\n for i in range(size):\n temp = queue.get()\n if level % 2 == 0:\n curr.append(temp.val)\n else:\n curr.insert(0, temp.val)\n if temp.left:\n queue.put(temp.left)\n if temp.right:\n queue.put(temp.right)\n level = not level\n output.append(curr)\n return output\n```\n```\n Give a \uD83D\uDC4D. It motivates me alot\n```\nLet\'s Connect On [Linkedin](https://www.linkedin.com/in/naman-agarwal-0551aa1aa/)
41
2
['Tree', 'Breadth-First Search', 'Binary Tree', 'C++', 'Python3']
8
binary-tree-zigzag-level-order-traversal
My Java Solution Beats 98%
my-java-solution-beats-98-by-biedengle2-6haa
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> res = new ArrayList();\n travel(res, 0, root);\n return
biedengle2
NORMAL
2016-03-16T19:34:41+00:00
2018-10-01T03:38:10.590066+00:00
13,761
false
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> res = new ArrayList();\n travel(res, 0, root);\n return res;\n }\n private void travel(List<List<Integer>> res, int level, TreeNode cur) {\n if (cur == null) return;\n if (res.size() <= level) {\n res.add(new ArrayList<Integer>());\n }\n if (level % 2 == 0) {\n res.get(level).add(cur.val);\n } else {\n res.get(level).add(0, cur.val);\n }\n travel(res, level + 1, cur.left);\n travel(res, level + 1, cur.right);\n }
37
1
['Breadth-First Search', 'Java']
6
binary-tree-zigzag-level-order-traversal
Java iterative and recursive solutions.
java-iterative-and-recursive-solutions-b-ltjd
\n // bfs \n public List<List<Integer>> zigzagLevelOrder1(TreeNode root) {\n List<List<Integer>> ret = new ArrayList<>();\n Queue<TreeNo
oldcodingfarmer
NORMAL
2016-05-07T07:56:46+00:00
2018-10-25T19:42:04.876984+00:00
9,754
false
\n // bfs \n public List<List<Integer>> zigzagLevelOrder1(TreeNode root) {\n List<List<Integer>> ret = new ArrayList<>();\n Queue<TreeNode> queue = new LinkedList<>();\n queue.add(root);\n int l = 0;\n while (!queue.isEmpty()) {\n int size = queue.size();\n List<Integer> level = new ArrayList<>();\n for (int i = 0; i < size; i++) {\n TreeNode node = queue.poll();\n if (node != null) {\n level.add(node.val);\n queue.add(node.left);\n queue.add(node.right);\n }\n }\n if (!level.isEmpty()) {\n if (l % 2 == 1) {\n Collections.reverse(level);\n }\n ret.add(level);\n }\n l++;\n }\n return ret;\n }\n \n // dfs recursively\n public List<List<Integer>> zigzagLevelOrder2(TreeNode root) {\n List<List<Integer>> ret = new ArrayList<>();\n dfs(root, 0, ret);\n return ret;\n }\n \n private void dfs(TreeNode node, int l, List<List<Integer>> ret) {\n if (node != null) {\n if (l == ret.size()) {\n List<Integer> level = new ArrayList<>();\n ret.add(level);\n }\n if (l % 2 == 1) {\n ret.get(l).add(0, node.val); // insert at the beginning\n } else {\n ret.get(l).add(node.val);\n }\n dfs(node.left, l+1, ret);\n dfs(node.right, l+1, ret);\n }\n }\n \n // dfs iteratively\n // import javafx.util.Pair;\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> ret = new ArrayList<>();\n Deque<Pair<TreeNode, Integer>> stack = new LinkedList<>();\n stack.push(new Pair(root, 0));\n while (!stack.isEmpty()) {\n Pair<TreeNode, Integer> p = stack.pop();\n TreeNode node = p.getKey();\n int l = p.getValue();\n if (node != null) {\n if (l == ret.size()) {\n ret.add(new ArrayList<>());\n }\n if (l % 2 == 1) {\n ret.get(l).add(0, node.val);\n } else {\n ret.get(l).add(node.val);\n }\n stack.push(new Pair(node.right, l+1));\n stack.push(new Pair(node.left, l+1));\n }\n }\n return ret;\n }
35
1
['Depth-First Search', 'Breadth-First Search', 'Java']
5
binary-tree-zigzag-level-order-traversal
JavaScript solution
javascript-solution-by-hongbo-miao-ymma
\nconst zigzagLevelOrder = (root) => {\n let res = [];\n\n const go = (node, lvl) => {\n if (node == null) return;\n if (res[lvl] == null) res[lvl] = []
hongbo-miao
NORMAL
2018-05-23T00:43:29.423454+00:00
2022-09-13T06:35:36.787337+00:00
4,412
false
```\nconst zigzagLevelOrder = (root) => {\n let res = [];\n\n const go = (node, lvl) => {\n if (node == null) return;\n if (res[lvl] == null) res[lvl] = [];\n\n if (lvl % 2 === 0) {\n res[lvl].push(node.val);\n } else {\n res[lvl].unshift(node.val);\n }\n\n go(node.left, lvl + 1);\n go(node.right, lvl + 1);\n };\n\n go(root, 0);\n return res;\n};\n```\n
34
0
['JavaScript']
5
binary-tree-zigzag-level-order-traversal
Day 50 || BFS || Easiest Beginner Friendly Sol
day-50-bfs-easiest-beginner-friendly-sol-52zs
Intuition of this Problem:\nThe problem asks us to perform a level-order traversal of a binary tree, but with a slight modification - we need to return the node
singhabhinash
NORMAL
2023-02-19T01:48:48.184130+00:00
2023-02-19T02:07:58.427963+00:00
3,035
false
# Intuition of this Problem:\nThe problem asks us to perform a level-order traversal of a binary tree, but with a slight modification - we need to return the nodes of each level in a zigzag order, starting from left to right and then right to left for the next level, and so on.\n\nThe intuition behind this problem is to use a queue-based BFS (Breadth First Search) approach to traverse the tree level by level, and maintain the order of the nodes in each level by keeping track of the level number. For every even numbered level, we add the nodes to the result list from left to right, and for every odd numbered level, we add the nodes to the result list from right to left.\n\nBy using this approach, we can ensure that we visit all the nodes in the tree in a level-order manner, while maintaining the zigzag order of the nodes at each level.\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem:\n1. If the root node is null, return an empty vector.\n2. Initialize a queue of type TreeNode* and push the root node into it.\n3. Initialize a variable to keep track of the current level (even or odd). We start with even level.\n4. While the queue is not empty:\n - a. Get the size of the queue and create a new vector to hold the elements of the current level.\n - b. Loop through the nodes at the current level and add their values to the vector.\n - c. If the current level is even, add the node\'s value to the end of the vector; otherwise, add it to the beginning.\n - d. If the node has a left child, add it to the queue.\n - e. If the node has a right child, add it to the queue.\n - f. Increment the level counter.\n - g. Add the vector containing the elements of the current level to the answer vector.\n1. Return the answer vector.\n<!-- Describe your approach to solving the problem. -->\n\n# Humble Request:\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** https://www.linkedin.com/in/abhinash-singh-1b851b188\n\n![57jfh9.jpg](https://assets.leetcode.com/users/images/c2826b72-fb1c-464c-9f95-d9e578abcaf3_1674104075.4732099.jpeg)\n\n# Code:\n```C++ []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n if (root == nullptr)\n return {};\n vector<vector<int>> ans;\n queue<TreeNode*> q;\n //strating from even level\n int isLevelEvenOrOdd = 0;\n q.push(root);\n while (!q.empty()) {\n int nodesInLevel = q.size();\n vector<int> tempVec;\n while (nodesInLevel--) {\n TreeNode* temp = q.front();\n q.pop();\n if (isLevelEvenOrOdd % 2 == 0) \n tempVec.push_back(temp -> val);\n else \n tempVec.insert(tempVec.begin(), temp -> val);\n \n if (temp -> left != nullptr)\n q.push(temp -> left);\n if (temp -> right != nullptr)\n q.push(temp -> right);\n } \n isLevelEvenOrOdd++;\n ans.push_back(tempVec);\n }\n return ans;\n }\n};\n```\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> result;\n if (root == nullptr) {\n return result;\n }\n queue<TreeNode*> q;\n q.push(root);\n bool left_to_right = true;\n while (!q.empty()) {\n int size = q.size();\n vector<int> level(size);\n for (int i = 0; i < size; i++) {\n TreeNode* node = q.front();\n q.pop();\n if (left_to_right)\n level[i] = node->val;\n else\n level[size - i - 1] = node->val;\n if (node->left) {\n q.push(node->left);\n }\n if (node->right) {\n q.push(node->right);\n }\n }\n result.push_back(level);\n left_to_right = !left_to_right;\n }\n return result;\n }\n};\n```\n```Java []\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> ans = new ArrayList<>();\n if (root == null)\n return ans;\n Queue<TreeNode> q = new LinkedList<>();\n q.offer(root);\n int level = 0;\n while (!q.isEmpty()) {\n int size = q.size();\n List<Integer> levelNodes = new ArrayList<>();\n while (size-- > 0) {\n TreeNode curr = q.poll();\n if (level % 2 == 0) {\n levelNodes.add(curr.val);\n } else {\n levelNodes.add(0, curr.val);\n }\n if (curr.left != null) {\n q.offer(curr.left);\n }\n if (curr.right != null) {\n q.offer(curr.right);\n }\n }\n level++;\n ans.add(levelNodes);\n }\n return ans;\n }\n}\n\n```\n```Python []\nclass Solution:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n q = collections.deque([root])\n level = 0\n ans = []\n while q:\n level_nodes = []\n for _ in range(len(q)):\n curr = q.popleft()\n if level % 2 == 0:\n level_nodes.append(curr.val)\n else:\n level_nodes.insert(0, curr.val)\n if curr.left:\n q.append(curr.left)\n if curr.right:\n q.append(curr.right)\n ans.append(level_nodes)\n level += 1\n return ans\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(n)**, where n is the number of nodes in the binary tree, since we need to traverse all the nodes.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(w)**, where w is the maximum width of the binary tree (i.e., the maximum number of nodes at any level). In the worst case, the queue will contain all the nodes at the last level, so the space complexity is proportional to the width of the tree.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
31
4
['Breadth-First Search', 'Binary Tree', 'C++', 'Java', 'Python3']
8
binary-tree-zigzag-level-order-traversal
Short and clear python code
short-and-clear-python-code-by-tusizi-9ndt
class Solution:\n # @param root, a tree node\n # @return a list of lists of integers\n def zigzagLevelOrder(self, root):\n queue = collections.d
tusizi
NORMAL
2015-02-18T16:57:24+00:00
2018-10-04T21:27:48.302743+00:00
7,741
false
class Solution:\n # @param root, a tree node\n # @return a list of lists of integers\n def zigzagLevelOrder(self, root):\n queue = collections.deque([root])\n res = []\n while queue:\n r = []\n for _ in range(len(queue)):\n q = queue.popleft()\n if q:\n r.append(q.val)\n queue.append(q.left)\n queue.append(q.right)\n r = r[::-1] if len(res) % 2 else r\n if r:\n res.append(r)\n return res
30
0
['Python']
4
binary-tree-zigzag-level-order-traversal
✅ JAVA solution
java-solution-by-coding_menance-eipc
Code\nJAVA []\npublic class Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) \n {\n List<List<Integer>> sol = new ArrayList<
coding_menance
NORMAL
2023-02-19T06:05:59.948690+00:00
2023-02-19T06:05:59.948734+00:00
3,120
false
# Code\n``` JAVA []\npublic class Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) \n {\n List<List<Integer>> sol = new ArrayList<>();\n travel(root, sol, 0);\n return sol;\n }\n \n private void travel(TreeNode curr, List<List<Integer>> sol, int level)\n {\n if(curr == null) return;\n \n if(sol.size() <= level)\n {\n List<Integer> newLevel = new LinkedList<>();\n sol.add(newLevel);\n }\n \n List<Integer> collection = sol.get(level);\n if(level % 2 == 0) collection.add(curr.val);\n else collection.add(0, curr.val);\n \n travel(curr.left, sol, level + 1);\n travel(curr.right, sol, level + 1);\n }\n}\n```\n\n![kitty.jpeg](https://assets.leetcode.com/users/images/4b501662-d825-408e-b0c1-dae2ae5b2132_1676786757.2180564.jpeg)\n
28
1
['Java']
2
binary-tree-zigzag-level-order-traversal
Two-stacks JavaScript solution
two-stacks-javascript-solution-by-jeanti-p94c
We can easily solve this problem using two stacks. The first stack s1 is used to traverse the current level of the tree, and the second stack s2 is used to trac
jeantimex
NORMAL
2017-10-12T23:46:50.341000+00:00
2017-10-12T23:46:50.341000+00:00
1,926
false
We can easily solve this problem using two stacks. The first stack `s1` is used to traverse the current level of the tree, and the second stack `s2` is used to track the nodes in the next level. Also, we need to have a `flag` to indicate the traversal direction has been flipped when the current level has been traversed completely.\n```\n/**\n * @param {TreeNode} root\n * @return {number[][]}\n */\nvar zigzagLevelOrder = function(root) {\n if (!root) return []; // Sanity check\n \n var result = [], level = [], s1 = [root], s2 = [], flag = true;\n \n while (s1.length > 0) {\n var node = s1.pop(), left = node.left, right = node.right;\n\n // Handle the current node\n level.push(node.val);\n\n // Get ready for the next level\n // the key of zigzag traversal is to control the order of pushing\n // left and right sub children\n if (flag) {\n if (left) s2.push(left);\n if (right) s2.push(right);\n } else {\n if (right) s2.push(right);\n if (left) s2.push(left);\n }\n \n // We just finish traversing the current level\n if (s1.length === 0) {\n result.push(level);\n level = [];\n flag = !flag;\n // Continue to traverse the next level\n s1 = s2;\n s2 = [];\n }\n }\n \n return result;\n};\n```\n\nTime complexity: `O(n)`\nSpace complexity: The max width of the tree
24
0
[]
3
binary-tree-zigzag-level-order-traversal
Javascript BFS
javascript-bfs-by-giddy-nw8v
Its a standard BFS with but the difference is we are keeping track of the depth at each level and that\'s determines if were adding to the front of the level a
giddy
NORMAL
2020-04-15T04:41:16.523999+00:00
2020-04-15T04:41:16.524040+00:00
2,458
false
Its a standard BFS with but the difference is we are keeping track of the depth at each level and that\'s determines if were adding to the front of the level array or the back of the level array. \n\n```\nvar zigzagLevelOrder = function(root) {\n if(!root) return [];\n let queue = [root];\n let output = [];\n let deep = 0;\n while(queue.length > 0){\n const size = queue.length;\n const level = [];\n \n for(let i=0; i< size; i++){\n const node = queue.shift();\n if(deep % 2 == 0) level.push(node.val);\n else level.unshift(node.val);\n \n if(node.left) queue.push(node.left)\n if(node.right) queue.push(node.right)\n }\n output.push(level)\n deep++;\n }\n \n \n return output\n \n \n};\n```
21
0
['Breadth-First Search', 'JavaScript']
2
binary-tree-zigzag-level-order-traversal
Python iterative BFS using deque
python-iterative-bfs-using-deque-by-work-awmm
With even or odd level, change the pop/append direction of the deque accordingly.\n\n```\nfrom collections import deque\nclass Solution:\n def zigzagLevelOrd
workcool
NORMAL
2020-12-09T00:19:04.452944+00:00
2020-12-09T00:19:04.452982+00:00
1,547
false
With even or odd level, change the pop/append direction of the deque accordingly.\n\n```\nfrom collections import deque\nclass Solution:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n \n dq = deque([root])\n res = []\n lvl = 0\n while dq:\n size = len(dq)\n curr = []\n for i in range(size):\n if lvl % 2 == 0:\n p = dq.popleft()\n curr.append(p.val)\n if p.left:\n dq.append(p.left)\n if p.right:\n dq.append(p.right)\n else:\n p = dq.pop()\n curr.append(p.val)\n if p.right:\n dq.appendleft(p.right)\n if p.left:\n dq.appendleft(p.left)\n res.append(curr)\n lvl += 1\n return res\n
20
0
[]
0
binary-tree-zigzag-level-order-traversal
Clean C++ solution using two stacks [1 ms]
clean-c-solution-using-two-stacks-1-ms-b-2yj1
\nclass Solution {\npublic:\n \n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n \n stack<TreeNode*> LtoR, RtoL;\n int lvl =
devangarora
NORMAL
2020-08-17T13:12:29.975485+00:00
2020-08-17T16:24:46.252853+00:00
1,874
false
```\nclass Solution {\npublic:\n \n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n \n stack<TreeNode*> LtoR, RtoL;\n int lvl = 1;\n \n vector<vector<int>> ans;\n \n if(!root) return ans;\n\n RtoL.push(root);\n\n while(!RtoL.empty() || !LtoR.empty()) {\n \n vector<int> v;\n \n if(lvl % 2 == 1) {\n \n while(!RtoL.empty()) {\n\n TreeNode* curr = RtoL.top();\n RtoL.pop();\n v.push_back(curr -> val);\n\n if(curr -> left) LtoR.push(curr -> left);\n if(curr -> right) LtoR.push(curr -> right); \n } \n\n } else {\n \n while(!LtoR.empty()) {\n\n TreeNode *curr = LtoR.top();\n LtoR.pop();\n v.push_back(curr -> val);\n\n if(curr -> right) RtoL.push(curr -> right);\n if(curr -> left) RtoL.push(curr -> left); \n } \n }\n \n ans.push_back(v);\n lvl++;\n \n }\n \n return ans;\n }\n};\n```
20
1
['C']
1
binary-tree-zigzag-level-order-traversal
Simple and clear python solution with explain
simple-and-clear-python-solution-with-ex-ug7s
I use a additional function addLevel to record the level number of nodes, then according to the level number, I can easily deal with the level order, see the co
qinzhou
NORMAL
2015-03-22T12:48:51+00:00
2015-03-22T12:48:51+00:00
6,967
false
I use a additional function addLevel to record the level number of nodes, then according to the level number, I can easily deal with the level order, see the code for details\n\n # Definition for a binary tree node\n # class TreeNode:\n # def __init__(self, x):\n # self.val = x\n # self.left = None\n # self.right = None\n \n class Solution:\n # @param root, a tree node\n # @return a list of lists of integers\n def zigzagLevelOrder(self, root):\n ans = []\n self.addLevel(ans, 0, root)#level from 0\n return ans\n \n \n def addLevel(self, ans, level, root):\n if not root:\n return\n elif len(ans) <= level:\n ans.append([root.val])\n elif not level%2:#if it is an even level, then then level ans should be inversed, so I use extend founction\n ans[level].extend([root.val])\n else:\n ans[level].insert(0,root.val)# if it is an odd level, then level ans should be ordinal, so I use insert function\n self.addLevel(ans, level + 1, root.left)\n self.addLevel(ans, level + 1, root.right)
20
1
['Python']
4
binary-tree-zigzag-level-order-traversal
Video solution | Actual zig zag traversal | Complete intuition in detail | C++
video-solution-actual-zig-zag-traversal-ey1iq
Video\nHey everyone i have created a video solution for this problem where we will actually traverse the binary tree in zig zag order , in the video i will be t
_code_concepts_
NORMAL
2024-08-06T11:02:22.656808+00:00
2024-08-06T13:32:35.089948+00:00
1,992
false
# Video\nHey everyone i have created a video solution for this problem where we will actually traverse the binary tree in zig zag order , in the video i will be taking you through the complete thought process and intuition for the video, do watch till the end for complete explanantion.\n\nVideo link: https://youtu.be/1fhszgcls5w\nPlaylist link: https://www.youtube.com/playlist?list=PLICVjZ3X1Aca0TjUTcsD7mobU001CE7GL \n\n\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> res;\n if(!root) return res;\n deque<TreeNode*> dq;\n int level=0;\n dq.push_back(root);\n while(!dq.empty()){\n int l=dq.size();\n vector<int> temp;\n for(int i=0;i<l;i++){\n if(level%2==0){\n TreeNode* node= dq.back();\n dq.pop_back();\n temp.push_back(node->val);\n if(node->left) dq.push_front(node->left);\n if(node->right) dq.push_front(node->right);\n\n }\n else{\n TreeNode* node= dq.front();\n dq.pop_front();\n temp.push_back(node->val);\n if(node->right) dq.push_back(node->right);\n if(node->left) dq.push_back(node->left);\n\n }\n }\n level++;\n res.push_back(temp);\n }\n\n \n\n return res;\n }\n};\n```
19
0
['C++']
0
binary-tree-zigzag-level-order-traversal
Simple java solution, 0ms,100 Faster, using queue, bfs
simple-java-solution-0ms100-faster-using-7ttk
\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x)
kushguptacse
NORMAL
2020-04-01T12:15:11.985697+00:00
2020-04-01T12:15:11.985728+00:00
2,098
false
```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> op = new LinkedList<>();\n if(root==null){\n return op;\n }\n Queue<TreeNode> queue = new LinkedList<>();\n queue.add(root);\n boolean odd=true;\n while(!queue.isEmpty()) {\n int size = queue.size();\n LinkedList<Integer> res = new LinkedList<>();\n for(int i=1;i<=size;i++){\n TreeNode node = queue.poll();\n if(odd){\n res.add(node.val); \n } else {\n res.addFirst(node.val);\n }\n if(node.left!=null) {\n queue.add(node.left);\n }\n if(node.right!=null){\n queue.add(node.right);\n }\n \n }\n op.add(res);\n odd=!odd;\n }\n return op;\n }\n}\n```
19
0
['Breadth-First Search', 'Queue', 'Java']
0
binary-tree-zigzag-level-order-traversal
Java O(n) time O(log n) space | BFS | single Deque | 1ms
java-on-time-olog-n-space-bfs-single-deq-5mvu
The main idea is to \n1. Read from Front : left-to-right\n2. Write to Rear the left child followed by the right child\n3. Read from Rear : right-to-left\n4. Wri
black-panther
NORMAL
2020-07-22T10:28:51.946473+00:00
2020-07-22T10:28:51.946505+00:00
2,317
false
The main idea is to \n1. Read from Front : left-to-right\n2. Write to Rear the left child followed by the right child\n3. Read from Rear : right-to-left\n4. Write to Front the right child followed by the left child\n\nAs each item is removed from either end of the queue it is added to the result list\n![image](https://assets.leetcode.com/users/images/c06f30df-9e15-4abb-ae17-6dc58a0f0e9f_1595413106.21344.png)\n```\npublic List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n if(root==null) {\n return Collections.emptyList();\n }\n \n ArrayDeque<TreeNode> deque = new ArrayDeque<>();\n\t\tList<List<Integer>> result = new ArrayList<>();\n List<Integer> row = null;\n\t\tTreeNode node = null;\n deque.addFirst(root);\n \n while(!deque.isEmpty()) {\n \n row = new ArrayList<>();\n result.add(row);\n int size = deque.size();\n\t\t\t\n while(size>0) {\n node = deque.removeFirst(); \n row.add(node.val);\n \n if(node.left!=null) {\n deque.addLast(node.left);\n }\n \n if(node.right!=null) {\n deque.addLast(node.right);\n }\n \n size--;\n }\n \n size = deque.size();\n if(size > 0) {\n row = new ArrayList<>();\n result.add(row);\n }\n \n while(size > 0) {\n node = deque.removeLast();\n row.add(node.val);\n \n if(node.right!=null) {\n deque.addFirst(node.right);\n }\n \n if(node.left!=null) {\n deque.addFirst(node.left);\n } \n \n size--;\n }\n }\n return result;\n }\n```\n\nTime Complexity : **O(n)** \nBecause, each item is put into the queue and read back only once.\nSpace Complexity: **O(log n)** \nBecause, in a complete binary tree for each removal, 2 addition will happen. Thus at any level with m nodes the queue will have at most 2m nodes.\nEg: a complete binary tree with 15 nodes, the queue will have a maximal length of 8 nodes.
18
1
['Breadth-First Search', 'Queue', 'Java']
0
binary-tree-zigzag-level-order-traversal
c++ Simple code using 2 stacks O(n)
c-simple-code-using-2-stacks-on-by-vinee-lszq
\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) { \n vector<vector<int>> ans;\n if(!root) return ans;\n stack<TreeNode*> dqL
vineet20
NORMAL
2021-10-25T10:20:53.388054+00:00
2021-10-25T10:20:53.388093+00:00
782
false
```\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) { \n vector<vector<int>> ans;\n if(!root) return ans;\n stack<TreeNode*> dqL;\n stack<TreeNode*> dqR;\n TreeNode* cur = root;\n dqL.push(cur);\n \n while(!dqL.empty() || !dqR.empty()){\n vector<int> curLevel; \n while(!dqL.empty()){\n cur = dqL.top();\n dqL.pop();\n curLevel.push_back(cur->val);\n if(cur->left) dqR.push(cur->left);\n if(cur->right) dqR.push(cur->right); \n }\n if(curLevel.size() > 0){\n ans.push_back(curLevel);\n curLevel.clear();\n }\n while(!dqR.empty()){\n cur = dqR.top();\n dqR.pop();\n curLevel.push_back(cur->val);\n if(cur->right) dqL.push(cur->right); \n if(cur->left) dqL.push(cur->left);\n }\n if(curLevel.size() > 0){ \n ans.push_back(curLevel);\n curLevel.clear(); \n } \n }\n \n return ans;\n```
17
0
[]
3
binary-tree-zigzag-level-order-traversal
Easy Python solution || Level order traversal
easy-python-solution-level-order-travers-026l
\tdef zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n\t\t\tif not root:\n\t\t\t\treturn []\n\t\t\tlevel = 1\n\t\t\tres, curr, nxt = [], [root], []
ItsMeSheersendu
NORMAL
2021-07-18T20:20:32.609775+00:00
2021-07-18T20:20:32.609813+00:00
1,509
false
\tdef zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n\t\t\tif not root:\n\t\t\t\treturn []\n\t\t\tlevel = 1\n\t\t\tres, curr, nxt = [], [root], [] \n\t\t\twhile curr:\n\t\t\t\tfor i in curr:\n\t\t\t\t\tif i.left:\n\t\t\t\t\t\tnxt.append(i.left)\n\t\t\t\t\tif i.right:\n\t\t\t\t\t\tnxt.append(i.right)\n\t\t\t\tif level%2 == 0:\n\t\t\t\t\tcurr.reverse()\n\t\t\t\tres.append([i.val for i in curr])\n\t\t\t\tcurr = nxt\n\t\t\t\tif nxt:\n\t\t\t\t\tlevel +=1\n\t\t\t\tnxt = []\n\t\t\treturn res\n\t\t\t\nHey you viewer, if you understand my solution, do **UPVOTE**, it motivates me. Keep practicing!!!
15
1
['Python', 'Python3']
1
binary-tree-zigzag-level-order-traversal
📌Easy C++ Solution | Just a small change in Level Order
easy-c-solution-just-a-small-change-in-l-hyav
Obervesion: We just need to reverse the alternate levels, rest is same as Level Ordering.\n\n\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrd
em_ashutosh
NORMAL
2021-06-07T12:52:25.371851+00:00
2021-08-22T18:13:51.623391+00:00
1,858
false
Obervesion: We just need to reverse the alternate levels, rest is same as Level Ordering.\n\n```\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) \n {\n vector <vector<int>> v;\n if(!root) // if root is null return\n return v;\n queue <TreeNode*> q;\n q.push(root);\n int count = 1; // we want reverse the list at alternate order\n while(!q.empty())\n {\n int n = q.size();\n vector <int> l;\n \n while(n--)\n {\n root=q.front();\n q.pop();\n l.push_back(root->val);\n if(root->left)\n q.push(root->left);\n if(root->right)\n q.push(root->right);\n }\n if(count%2==0) // we want reverse the list at alternate order\n reverse(l.begin(),l.end());\n v.push_back(l);\n count++;\n }\n \n return v;\n \n }\n};\n```\n
15
1
['C', 'C++']
1
binary-tree-zigzag-level-order-traversal
C++ BFS
c-bfs-by-rohitsaraf17-3sal
\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> ans;\n if(root == NULL)\n
rohitsaraf17
NORMAL
2020-01-05T23:06:39.882635+00:00
2020-01-05T23:06:39.882674+00:00
2,051
false
```\nclass Solution {\npublic:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> ans;\n if(root == NULL)\n return ans;\n queue<TreeNode*> info;\n info.push(root);\n bool flag = false;\n while(!info.empty()){\n int n = info.size();\n vector<int> inter;\n for(; n>0; n--){\n TreeNode* top = info.front();\n info.pop();\n if(top->left != NULL)\n info.push(top->left);\n if(top->right != NULL)\n info.push(top->right);\n inter.push_back(top->val);\n }\n if(flag)\n reverse(inter.begin(), inter.end());\n ans.push_back(inter);\n flag = !flag;\n }\n return ans;\n }\n};\n```
15
0
['Breadth-First Search', 'C']
6
binary-tree-zigzag-level-order-traversal
Python easy to understand deque solution
python-easy-to-understand-deque-solution-yvmx
\nclass Solution(object):\n def zigzagLevelOrder(self, root):\n deque = collections.deque()\n if root:\n deque.append(root)\n
oldcodingfarmer
NORMAL
2015-07-14T19:43:28+00:00
2020-10-15T14:26:21.118133+00:00
3,808
false
```\nclass Solution(object):\n def zigzagLevelOrder(self, root):\n deque = collections.deque()\n if root:\n deque.append(root)\n res, level = [], 0\n while deque:\n l, size = [], len(deque)\n for _ in range(size): # process level by level\n node = deque.popleft()\n l.append(node.val)\n if node.left:\n deque.append(node.left)\n if node.right:\n deque.append(node.right)\n if level % 2 == 1:\n l.reverse()\n res.append(l)\n level += 1\n return res\n```
15
0
['Breadth-First Search', 'Queue', 'Python']
3
binary-tree-zigzag-level-order-traversal
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
leetcode-the-hard-way-explained-line-by-o53hh
\uD83D\uDD34 Check out LeetCode The Hard Way for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our Discord Study Group for live discussion.
__wkw__
NORMAL
2023-02-19T03:04:14.912837+00:00
2023-02-19T03:04:14.912887+00:00
2,361
false
\uD83D\uDD34 Check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord Study Group](https://discord.gg/Nqm4jJcyBf) for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post if you like it.\n\uD83D\uDD35 Check out [Screencast](https://www.youtube.com/watch?v=SDFFhfwEIiY&list=PLBu4Bche1aEU-8z7xl3-B9lfw_DJtT_xs&index=19) if you are interested.\n\n---\n\n```py\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n # Level traversal -> BFS\n # reverse the list for odd-index level\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n # if there is no root, then return []\n if not root: return []\n # init ans and queue with initial node `root`\n ans, q = [], [root]\n # BFS\n while q:\n # direction - 1 for even-index level and -1 for odd-index level\n d = -1 if len(ans) % 2 == 1 else 1\n # put all node values to a list with the correct direction \n # and add to `ans` \n ans.append([n.val for n in q][::d])\n # for each node in the queue, \n # we add the left or right node to the queue if applicable\n q = [n for node in q for n in (node.left, node.right) if n]\n return ans\n```
14
2
['Breadth-First Search', 'Python']
3
binary-tree-zigzag-level-order-traversal
My AC Java code
my-ac-java-code-by-lurklurk-0lwl
I use two stacks, one for processing current layer and one for storing nodes for the next layer. I also use a flag (order in your code) to indicate the directio
lurklurk
NORMAL
2014-09-13T20:22:57+00:00
2014-09-13T20:22:57+00:00
5,057
false
I use two stacks, one for processing current layer and one for storing nodes for the next layer. I also use a flag (order in your code) to indicate the direction. It is straightforward\n\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n List<List<Integer>> output = new ArrayList<List<Integer>>();\n if (root == null) return output;\n Stack<TreeNode> cur_layer = new Stack<TreeNode>(); cur_layer.push(root);\n Stack<TreeNode> next_layer = new Stack<TreeNode>();\n List<Integer> layer_output = new ArrayList<Integer>();\n int d = 0; // 0: left to right; 1: right to left.\n \n while (!cur_layer.isEmpty()){\n \tTreeNode node = cur_layer.pop();\n \tlayer_output.add(node.val);\n \tif(d==0){\n \t\tif (node.left != null) next_layer.push(node.left);\n \t\tif (node.right != null) next_layer.push(node.right);\n \t}else{\n \t\tif (node.right != null) next_layer.push(node.right);\n \t\tif (node.left != null) next_layer.push(node.left);\n \t}\n \t\n \tif (cur_layer.isEmpty()){\n \t\toutput.add(layer_output);\n \t\tlayer_output = new ArrayList<Integer>();\n \t\tcur_layer = next_layer;\n \t\tnext_layer = new Stack<TreeNode>();;\n \t\td ^= 1;\n \t}\n }\n return output;\n }
14
0
[]
2
binary-tree-zigzag-level-order-traversal
[recommend for beginners]clean C++ implementation with detailed explanation
recommend-for-beginnersclean-c-implement-1h4n
class Solution {\n public:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> result;\n if(!root) re
rainbowsecret
NORMAL
2016-01-27T13:27:03+00:00
2018-10-26T02:13:25.211267+00:00
3,585
false
class Solution {\n public:\n vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n vector<vector<int>> result;\n if(!root) return result;\n deque<TreeNode*> tree;\n tree.push_back(root);\n int flag=0;\n while(!tree.empty()){\n int count=tree.size();\n vector<int> level;\n while(count-- > 0){\n TreeNode* cur=tree.front();\n tree.pop_front();\n level.push_back(cur->val);\n if(cur->left) tree.push_back(cur->left);\n if(cur->right) tree.push_back(cur->right);\n }\n if(flag & 1) reverse(level.begin(), level.end());\n result.push_back(level);\n flag++;\n }\n return result;\n }\n };
14
11
[]
6
binary-tree-zigzag-level-order-traversal
✔️ 100% Fastest Swift Solution, time: O(n), space: O(n).
100-fastest-swift-solution-time-on-space-4qjo
\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public var val: Int\n * public var left: TreeNode?\n * public var right
sergeyleschev
NORMAL
2022-04-09T05:44:54.430598+00:00
2022-04-09T05:44:54.430645+00:00
486
false
```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public var val: Int\n * public var left: TreeNode?\n * public var right: TreeNode?\n * public init() { self.val = 0; self.left = nil; self.right = nil; }\n * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }\n * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {\n * self.val = val\n * self.left = left\n * self.right = right\n * }\n * }\n */\nclass Solution {\n // - Complexity:\n // - time: O(n), where n is the number of nodes.\n // - space: O(n), where n is the number of nodes.\n\n func zigzagLevelOrder(_ root: TreeNode?) -> [[Int]] {\n var ans = [[Int]]()\n dfs(root, level: 0, ans: &ans)\n return ans\n }\n\n\n private func dfs(_ node: TreeNode?, level: Int, ans: inout [[Int]]) {\n guard let node = node else { return }\n if ans.count <= level { ans.append([Int]()) }\n\n if level % 2 == 0 {\n ans[level].append(node.val)\n } else {\n ans[level].insert(node.val, at: 0)\n }\n\n dfs(node.left, level: level + 1, ans: &ans)\n dfs(node.right, level: level + 1, ans: &ans)\n }\n\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful.
13
0
['Swift']
1
binary-tree-zigzag-level-order-traversal
0ms beats 100%. Easy to understand recursive solution.
0ms-beats-100-easy-to-understand-recursi-bq6s
\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x)
gullible_frog
NORMAL
2019-11-25T03:39:55.012508+00:00
2019-11-25T03:41:09.525837+00:00
1,356
false
```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\nclass Solution {\n public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n \n List<List<Integer>> res = new ArrayList<>();\n zigzagHelp(root, 0, res);\n return res;\n \n }\n \n public void zigzagHelp(TreeNode root, int level, List<List<Integer>> list) {\n \n if (root == null) {\n return;\n }\n \n if (list.size() <= level) {\n list.add(new ArrayList<>()); \n } \n \n if (level % 2 == 0) {\n list.get(level).add(root.val);\n }\n else {\n list.get(level).add(0, root.val); \n }\n \n zigzagHelp(root.left, level + 1, list);\n zigzagHelp(root.right, level + 1, list);\n \n }\n}\n```
13
0
['Recursion', 'Java']
3
binary-tree-zigzag-level-order-traversal
C++ ✅ || Beats 100%💯 || Fast Solution🔥|| Simple Code🚀
c-beats-100-fast-solution-simple-code-by-z867
🌟 Intuition"Let's go zigzag through the tree, level by level!" This problem is like navigating a forest, but with a twist! Instead of moving straight, we need t
yashm01
NORMAL
2024-12-27T08:11:46.812160+00:00
2024-12-27T08:11:46.812160+00:00
1,723
false
![Screenshot 2024-12-27 133942.png](https://assets.leetcode.com/users/images/6730777b-bde8-4e03-a62a-88363e92d832_1735287033.327401.png) # 🌟 Intuition *"Let's go zigzag through the tree, level by level!"* This problem is like navigating a forest, but with a twist! Instead of moving straight, we need to alternate our direction as we go down the tree. At each level, the traversal should go left-to-right for one level, then right-to-left for the next. Think of it as weaving through the branches in a snake-like pattern! 🐍 # 🚀 Approach 1. Perform a level order traversal (BFS) to capture the nodes at each level. 2. Use a flag (`level % 2 == 0`) to determine if we need to reverse the order of the current level. - Even levels are left-to-right. - Odd levels are right-to-left. 3. Store nodes in a vector of vectors to keep track of each level's traversal. # 📊 Complexity - **Time Complexity:** $$O(n)$$ 🕒 — We visit each node once. - **Space Complexity:** $$O(n)$$ 📦 — The space required for the result and the recursive call stack is proportional to the number of nodes. # 💻 Code ```cpp class Solution { public: void solve(vector<vector<int>>& ans, TreeNode* temp, int level) { if (temp == NULL) return; if (ans.size() <= level) ans.push_back({}); if (level % 2 == 0) ans[level].push_back(temp->val); else ans[level].insert(ans[level].begin(), temp->val); solve(ans, temp->left, level + 1); solve(ans, temp->right, level + 1); } vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> ans; solve(ans, root, 0); return ans; } }; ``` ![upvote.jpeg](https://assets.leetcode.com/users/images/497d3107-f1ae-4d61-8553-d5f277772a44_1735287018.473409.jpeg)
12
0
['Tree', 'Breadth-First Search', 'Binary Tree', 'C++']
0