Files
org_backend/output/20250804212606-leetcode_arrays.html
2025-12-28 20:55:38 +00:00

791 lines
21 KiB
HTML
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<!-- 2025-12-28 Sun 20:54 -->
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>leetcode-arrays</title>
<meta name="generator" content="Org Mode" />
<style type="text/css">
#content { max-width: 60em; margin: auto; }
.title { text-align: center;
margin-bottom: .2em; }
.subtitle { text-align: center;
font-size: medium;
font-weight: bold;
margin-top:0; }
.todo { font-family: monospace; color: red; }
.done { font-family: monospace; color: green; }
.priority { font-family: monospace; color: orange; }
.tag { background-color: #eee; font-family: monospace;
padding: 2px; font-size: 80%; font-weight: normal; }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.org-right { margin-left: auto; margin-right: 0px; text-align: right; }
.org-left { margin-left: 0px; margin-right: auto; text-align: left; }
.org-center { margin-left: auto; margin-right: auto; text-align: center; }
.underline { text-decoration: underline; }
#postamble p, #preamble p { font-size: 90%; margin: .2em; }
p.verse { margin-left: 3%; }
pre {
border: 1px solid #e6e6e6;
border-radius: 3px;
background-color: #f2f2f2;
padding: 8pt;
font-family: monospace;
overflow: auto;
margin: 1.2em;
}
pre.src {
position: relative;
overflow: auto;
}
pre.src:before {
display: none;
position: absolute;
top: -8px;
right: 12px;
padding: 3px;
color: #555;
background-color: #f2f2f299;
}
pre.src:hover:before { display: inline; margin-top: 14px;}
/* Languages per Org manual */
pre.src-asymptote:before { content: 'Asymptote'; }
pre.src-awk:before { content: 'Awk'; }
pre.src-authinfo::before { content: 'Authinfo'; }
pre.src-C:before { content: 'C'; }
/* pre.src-C++ doesn't work in CSS */
pre.src-clojure:before { content: 'Clojure'; }
pre.src-css:before { content: 'CSS'; }
pre.src-D:before { content: 'D'; }
pre.src-ditaa:before { content: 'ditaa'; }
pre.src-dot:before { content: 'Graphviz'; }
pre.src-calc:before { content: 'Emacs Calc'; }
pre.src-emacs-lisp:before { content: 'Emacs Lisp'; }
pre.src-fortran:before { content: 'Fortran'; }
pre.src-gnuplot:before { content: 'gnuplot'; }
pre.src-haskell:before { content: 'Haskell'; }
pre.src-hledger:before { content: 'hledger'; }
pre.src-java:before { content: 'Java'; }
pre.src-js:before { content: 'Javascript'; }
pre.src-latex:before { content: 'LaTeX'; }
pre.src-ledger:before { content: 'Ledger'; }
pre.src-lisp:before { content: 'Lisp'; }
pre.src-lilypond:before { content: 'Lilypond'; }
pre.src-lua:before { content: 'Lua'; }
pre.src-matlab:before { content: 'MATLAB'; }
pre.src-mscgen:before { content: 'Mscgen'; }
pre.src-ocaml:before { content: 'Objective Caml'; }
pre.src-octave:before { content: 'Octave'; }
pre.src-org:before { content: 'Org mode'; }
pre.src-oz:before { content: 'OZ'; }
pre.src-plantuml:before { content: 'Plantuml'; }
pre.src-processing:before { content: 'Processing.js'; }
pre.src-python:before { content: 'Python'; }
pre.src-R:before { content: 'R'; }
pre.src-ruby:before { content: 'Ruby'; }
pre.src-sass:before { content: 'Sass'; }
pre.src-scheme:before { content: 'Scheme'; }
pre.src-screen:before { content: 'Gnu Screen'; }
pre.src-sed:before { content: 'Sed'; }
pre.src-sh:before { content: 'shell'; }
pre.src-sql:before { content: 'SQL'; }
pre.src-sqlite:before { content: 'SQLite'; }
/* additional languages in org.el's org-babel-load-languages alist */
pre.src-forth:before { content: 'Forth'; }
pre.src-io:before { content: 'IO'; }
pre.src-J:before { content: 'J'; }
pre.src-makefile:before { content: 'Makefile'; }
pre.src-maxima:before { content: 'Maxima'; }
pre.src-perl:before { content: 'Perl'; }
pre.src-picolisp:before { content: 'Pico Lisp'; }
pre.src-scala:before { content: 'Scala'; }
pre.src-shell:before { content: 'Shell Script'; }
pre.src-ebnf2ps:before { content: 'ebfn2ps'; }
/* additional language identifiers per "defun org-babel-execute"
in ob-*.el */
pre.src-cpp:before { content: 'C++'; }
pre.src-abc:before { content: 'ABC'; }
pre.src-coq:before { content: 'Coq'; }
pre.src-groovy:before { content: 'Groovy'; }
/* additional language identifiers from org-babel-shell-names in
ob-shell.el: ob-shell is the only babel language using a lambda to put
the execution function name together. */
pre.src-bash:before { content: 'bash'; }
pre.src-csh:before { content: 'csh'; }
pre.src-ash:before { content: 'ash'; }
pre.src-dash:before { content: 'dash'; }
pre.src-ksh:before { content: 'ksh'; }
pre.src-mksh:before { content: 'mksh'; }
pre.src-posh:before { content: 'posh'; }
/* Additional Emacs modes also supported by the LaTeX listings package */
pre.src-ada:before { content: 'Ada'; }
pre.src-asm:before { content: 'Assembler'; }
pre.src-caml:before { content: 'Caml'; }
pre.src-delphi:before { content: 'Delphi'; }
pre.src-html:before { content: 'HTML'; }
pre.src-idl:before { content: 'IDL'; }
pre.src-mercury:before { content: 'Mercury'; }
pre.src-metapost:before { content: 'MetaPost'; }
pre.src-modula-2:before { content: 'Modula-2'; }
pre.src-pascal:before { content: 'Pascal'; }
pre.src-ps:before { content: 'PostScript'; }
pre.src-prolog:before { content: 'Prolog'; }
pre.src-simula:before { content: 'Simula'; }
pre.src-tcl:before { content: 'tcl'; }
pre.src-tex:before { content: 'TeX'; }
pre.src-plain-tex:before { content: 'Plain TeX'; }
pre.src-verilog:before { content: 'Verilog'; }
pre.src-vhdl:before { content: 'VHDL'; }
pre.src-xml:before { content: 'XML'; }
pre.src-nxml:before { content: 'XML'; }
/* add a generic configuration mode; LaTeX export needs an additional
(add-to-list 'org-latex-listings-langs '(conf " ")) in .emacs */
pre.src-conf:before { content: 'Configuration File'; }
table { border-collapse:collapse; }
caption.t-above { caption-side: top; }
caption.t-bottom { caption-side: bottom; }
td, th { vertical-align:top; }
th.org-right { text-align: center; }
th.org-left { text-align: center; }
th.org-center { text-align: center; }
td.org-right { text-align: right; }
td.org-left { text-align: left; }
td.org-center { text-align: center; }
dt { font-weight: bold; }
.footpara { display: inline; }
.footdef { margin-bottom: 1em; }
.figure { padding: 1em; }
.figure p { text-align: center; }
.equation-container {
display: table;
text-align: center;
width: 100%;
}
.equation {
vertical-align: middle;
}
.equation-label {
display: table-cell;
text-align: right;
vertical-align: middle;
}
.inlinetask {
padding: 10px;
border: 2px solid gray;
margin: 10px;
background: #ffffcc;
}
#org-div-home-and-up
{ text-align: right; font-size: 70%; white-space: nowrap; }
textarea { overflow-x: auto; }
.linenr { font-size: smaller }
.code-highlighted { background-color: #ffff00; }
.org-info-js_info-navigation { border-style: none; }
#org-info-js_console-label
{ font-size: 10px; font-weight: bold; white-space: nowrap; }
.org-info-js_search-highlight
{ background-color: #ffff00; color: #000000; font-weight: bold; }
.org-svg { }
</style>
<link rel="stylesheet" href="/assets/styles/style.css" />
<link rel="stylesheet" href="/assets/styles/bigger-picture.min.css" />
<link rel="stylesheet" href="/assets/styles/media.css" />
<script src="/assets/scripts/script.js" defer></script>
<script src="/assets/scripts/search.js" defer></script>
<script src="/assets/scripts/bigger-picture.min.js" defer></script>
<script src="/assets/scripts/svg-pan-zoom.min.js" defer></script>
<script src="/assets/scripts/gallery-init.js" defer></script>
</head>
<body>
<div id="preamble" class="status">
<div class="banner-header">
<div class="banner-left">
<a href="/20241210233721-brain_moc.html"> <img src="/assets/gr.png" alt="Site Logo" class="banner-logo" /> </a>
<div id="updated">Updated: 2025-12-28 Sun 19:48</div>
</div>
<div class="banner-search">
<input id="search-box"
type="search"
placeholder="Search notes…"
aria-label="Search notes"
autocomplete="off" />
<div id="search-results"></div>
</div>
<button id="close-all">Close All</button>
</div>
</div>
<div id="stack-root">
<div class="stack-track">
<article class="stack-pane pane-root" data-url="/20250804212606-leetcode_arrays.html">
<div id="content" class="content">
<div class="title-section">
<div class="title-controls">
<button class="pane-fullscreen" aria-label="Fullscreen">F</button>
<button class="pane-edit" aria-label="Edit pane">E</button>
<button class="pane-close" aria-label="Close pane">×</button>
</div>
<h1 class="title">leetcode-arrays</h1>
<div class="title-metadata">
<span class="metadata-item">
<span class="metadata-label">planted:</span>
<span class="metadata-value">2025-08-04</span>
</span>
<span class="metadata-item">
<span class="metadata-label">last tended to:</span>
<span class="metadata-value">2025-12-28</span>
</span>
</div>
</div>
<div id="outline-container-org84adef0" class="outline-2">
<h2 id="org84adef0"><a href="#org84adef0">217 - Contains Duplicate:</a></h2>
<div class="outline-text-2" id="text-org84adef0">
<p>
Given an integer array `nums`, return `true` if any value appears at least twice in the array, and return false if every element is distinct.
</p>
<p>
<b>Example 1:</b>
</p>
<p>
Input: nums = [1,2,3,1]
</p>
<p>
Output: true
</p>
<p>
Explanation: The element 1 occurs at the indices 0 and 3.
</p>
<p>
<b>Example 2:</b>
</p>
<p>
Input: nums = [1,2,3,4]
</p>
<p>
Output: false
</p>
<p>
Explanation: All elements are distinct.
</p>
<p>
<b>Example 3:</b>
</p>
<p>
Input: nums = [1,1,1,3,3,4,3,2,4,2]
</p>
<p>
Output: true
</p>
<p>
<b>Constraints:</b>
</p>
<p>
1 &lt;= nums.length &lt;= 105
-109 &lt;= nums[i] &lt;= 109
</p>
</div>
<div id="outline-container-org57984c7" class="outline-3">
<h3 id="org57984c7"><a href="#org57984c7">Attempt:</a></h3>
<div class="outline-text-3" id="text-org57984c7">
<p>
Two loops
Outer loop will go through each element, inner loop will check if the element in outer loop is repeated in the array.
</p>
<div class="org-src-container">
<pre class="src src-python">class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
for i in nums:
for j in nums[i:len(nums)]:
if i == j:
return True
return False
</pre>
</div>
<p>
Works? Yes, but there is a better solution
</p>
</div>
</div>
<div id="outline-container-org8d98ae5" class="outline-3">
<h3 id="org8d98ae5"><a href="#org8d98ae5">Solution:</a></h3>
<div class="outline-text-3" id="text-org8d98ae5">
<p>
Use a <a href="20250804214537-python_set.html#ID-3a41407c-661e-416a-80d2-4c7a137d153a">python-set</a>. The reason is it does not allow for duplicates (it is unique). The solution is as follows:
We create a set from the array, then check if the length of the two are different, if they are then this indicates that there are duplicate values in the array. This is O(N) and is faster than the nested loops solution above.
</p>
<div class="org-src-container">
<pre class="src src-python">
if len(set(nums)) == len(nums):
return False
else:
return True
</pre>
</div>
</div>
</div>
</div>
<div id="outline-container-org7e81f93" class="outline-2">
<h2 id="org7e81f93"><a href="#org7e81f93">268 - Missing Number</a></h2>
<div class="outline-text-2" id="text-org7e81f93">
<p>
Given an array `nums` containing `n` distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
</p>
<p>
Example 1:
Input: nums = [3,0,1]
</p>
<p>
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
</p>
<p>
Example 2:
Input: nums = [0,1]
</p>
<p>
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
</p>
<p>
Example 3:
Input: nums = [9,6,4,2,3,5,7,0,1]
</p>
<p>
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
</p>
<p>
Constraints:
</p>
<p>
n <code>= nums.length
1 &lt;</code> n &lt;= 104
0 &lt;= nums[i] &lt;= n
All the numbers of nums are unique.
</p>
<p>
Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
</p>
</div>
<div id="outline-container-orgad55f8f" class="outline-3">
<h3 id="orgad55f8f"><a href="#orgad55f8f">Attempt</a></h3>
<div class="outline-text-3" id="text-orgad55f8f">
<p>
Sort the array, loop through it and check via the incrementor
</p>
<div class="org-src-container">
<pre class="src src-python">
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
for i in range(0, len(nums) + 1):
if i not in nums:
return i
</pre>
</div>
<p>
Problem here is that sort operation is O(nlogn) - too slow.
</p>
</div>
</div>
<div id="outline-container-org9674e04" class="outline-3">
<h3 id="org9674e04"><a href="#org9674e04">Solution</a></h3>
<div class="outline-text-3" id="text-org9674e04">
<p>
One optimised solution:
</p>
<div class="org-src-container">
<pre class="src src-python">class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
n = len(nums)
total_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return total_sum - actual_sum
</pre>
</div>
<p>
Another:
</p>
<div class="org-src-container">
<pre class="src src-python">class Solution(object):
def missingNumber(self, nums):
return sum(range(len(nums) + 1)) - sum(nums)
</pre>
</div>
<p>
This is O(N)
len = O(1)
Range object creation is O(1)
sum is O(N)
+1 in range(n) because n would be excluded otherwise. ie if you did range(2) you get [0,1]
</p>
<p>
Some extra notes:
<a href="20250805141906-python_dictionary.html#ID-125c81dc-c14f-4b4d-93c6-0a2b157735ac">python-dictionary</a>
</p>
</div>
</div>
</div>
<div id="outline-container-org4966b4f" class="outline-2">
<h2 id="org4966b4f"><a href="#org4966b4f">448 - Find all Numbers disappeared in an array</a></h2>
<div class="outline-text-2" id="text-org4966b4f">
<p>
Given an array `nums` of `n` integers where `nums[i]` is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.
</p>
<p>
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
</p>
<p>
Example 2:
Input: nums = [1,1]
Output: [2]
</p>
<p>
Constraints:
</p>
<p>
n <code>= nums.length
1 &lt;</code> n &lt;= 105
1 &lt;= nums[i] &lt;= n
</p>
<p>
Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
</p>
</div>
<div id="outline-container-org6ba1d2f" class="outline-3">
<h3 id="org6ba1d2f"><a href="#org6ba1d2f">Attempt</a></h3>
<div class="outline-text-3" id="text-org6ba1d2f">
<p>
Create a set, loop through the set (it wont have duplicate values), if the counter is not equal to the value in the set, add it to a new list.
</p>
<div class="org-src-container">
<pre class="src src-python">class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
new_set = set(nums)
print(new_set)
new_list = []
for i in range(1, len(nums) + 1):
if i not in new_set:
new_list.append(i)
return new_list
</pre>
</div>
<p>
Time: O(N) as iterating through the range and appending to new list if not in given list. O(N) space.
</p>
</div>
</div>
</div>
<div id="outline-container-org82e9c52" class="outline-2">
<h2 id="org82e9c52"><a href="#org82e9c52">1 - Two Sum</a></h2>
<div class="outline-text-2" id="text-org82e9c52">
<p>
Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to target.
</p>
<p>
You may assume that each input would have exactly one solution, and you may not use the same element twice.
</p>
<p>
You can return the answer in any order.
</p>
<p>
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
</p>
<p>
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
</p>
<p>
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
</p>
<p>
Constraints:
</p>
<p>
2 &lt;= nums.length &lt;= 104
-109 &lt;= nums[i] &lt;= 109
-109 &lt;= target &lt;= 109
Only one valid answer exists.
</p>
<p>
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
</p>
</div>
<div id="outline-container-orgad99534" class="outline-3">
<h3 id="orgad99534"><a href="#orgad99534">Attempt</a></h3>
<div class="outline-text-3" id="text-orgad99534">
<p>
Outer loop and inner loop
</p>
<div class="org-src-container">
<pre class="src src-python">class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ret = []
for i in range(0, len(nums) ):
for j in range(i + 1, len(nums) ):
if nums[i] + nums[j] == target:
ret.append(nums[i])
ret.append(nums[j])
return ret
</pre>
</div>
<p>
Bad as its O(N<sup>2</sup>)
</p>
</div>
</div>
<div id="outline-container-org902927a" class="outline-3">
<h3 id="org902927a"><a href="#org902927a">Solution</a></h3>
<div class="outline-text-3" id="text-org902927a">
<p>
Use a hashmap and loop once
</p>
<p>
After looking through the logic:
</p>
<div class="org-src-container">
<pre class="src src-python">class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hm = {}
ret = []
for i in range(0, len(nums)):
if (target - nums[i]) not in hm:
hm.update({nums[i]: i})
else:
ret.append(i)
ret.append(hm.get(target - nums[i]))
return ret
</pre>
</div>
<div id="orge7a3750" class="figure">
<p><img src="assets/swappy-20250805-152411.png" alt="swappy-20250805-152411.png" />
</p>
</div>
<p>
Youtube solution:
</p>
<div class="org-src-container">
<pre class="src src-python">
hash_map = {}
for i , v in enumerate(nums):
if target - v in hash_map:
return i, hash_map[target - v]
else:
hash_map[v] = i
</pre>
</div>
<div class="org-src-container">
<pre class="src src-python">
hashMap = {}
for indx, val in enumerate(nums):
diff = target - val
if diff in hashMap:
return [indx, hashMap[diff]]
hashMap[val] = indx
</pre>
</div>
</div>
</div>
</div>
<div id="outline-container-org94989f9" class="outline-2">
<h2 id="org94989f9"><a href="#org94989f9">1365 - How Many Numbers Are Smaller Than the Current Number</a></h2>
<div class="outline-text-2" id="text-org94989f9">
<p>
Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid j&rsquo;s such that j != i and nums[j] &lt; nums[i].
</p>
<p>
Return the answer in an array.
</p>
<p>
Example 1:
</p>
<p>
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
</p>
<p>
Example 2:
</p>
<p>
Input: nums = [6,5,4,8]
Output: [2,1,0,3]
</p>
<p>
Example 3:
</p>
<p>
Input: nums = [7,7,7,7]
Output: [0,0,0,0]
</p>
<p>
Constraints:
</p>
<p>
2 &lt;= nums.length &lt;= 500
0 &lt;= nums[i] &lt;= 100
</p>
<div class="org-src-container">
<pre class="src src-python">def smallerNumbersThanCurrent(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
temp = sorted(nums)
d = {}
for i, num in enumerate(temp):
if num not in d:
d[num] = i
ret = []
for i in nums:
ret.append(d[i])
return ret
</pre>
</div>
<p class="backlinks-section" id="backlinks">
Backlinks
</p>
<ul class="org-ul backlinks-list">
<li><a href="20241210001206-leetcode_notes.html#ID-9d1cfccc-8da7-41a3-b435-9857f0abe441">leetcode<sub>notes</sub></a></li>
</ul>
</div>
</div>
</div>
</div></article></div></div>
<div id="postamble" class="status">
<footer>
<div class="copyright-container">
<div class="copyright">
Copyright &copy; 2022-2025 Zaine Qayyum. All rights reserved unless otherwise noted.</div></div>
<div class="generated">
Created with <a href="https://www.gnu.org/software/emacs/">Emacs</a> 30.2 (<a href="https://orgmode.org">Org</a> mode 9.7.11) on <a href="https://www.archlinux.org/">Arch</a> <a href="https://www.gnu.org">GNU</a>/<a href="https://www.kernel.org/">Linux</a>
</div>
</footer>
</div>
</body>
</html>