fabiochiu/medium-articles huggingface dataset:
Housing Is A Human Right Wins ‘Best Activism Journalism’ Award
By: Housing Is A Human Right
Tags: News, Gentrification, Politics, Housing, California

Housing Is A Human Right and Patrick Range McDonald, the organization’s advocacy journalist, recently won the “Best Activism Journalism” award from the Los Angeles Press Club. HHR and McDonald earned the honor for the 2019 investigative report on L.A.’s gentrification crisis, titled “The Garcetti-fication of Los Angeles: A Gentrification Cautionary Tale.”

Housing Is A Human Right is the housing advocacy division of AIDS Healthcare Foundation, the world’s largest HIV/AIDS medical-care nonprofit. For decades, AHF’s mission has been to provide “cutting-edge advocacy” to create long-term policy change. Housing Is A Human Right’s award-winning report, which was researched and written by McDonald, is another example of carrying out that vital work.

The investigation examined government-sanctioned gentrification in Los Angeles and how Mayor Eric Garcetti played a central role.

“At the end of his inauguration speech, as the sky grew dark, Mayor Eric Garcetti boasted that Los Angeles is a ‘paradise,’” McDonald wrote. “In truth, the nation’s second largest city had become a high-profile cautionary tale about modern-day gentrification in California and throughout the United States — and how politicians vigorously push it through. It’s a story that took place over years and often behind closed doors, but can no longer be ignored. Too many lives — in L.A. and across the country — hang in the balance.”

The Housing Is A Human Right report explained that Garcetti and L.A. City Council members have long embraced a “build, baby, build” agenda that pushed for the widespread construction of luxury housing, regardless of its negative impacts on middle- and working-class residents. For years, housing justice activists have said that City Hall’s luxury-housing agenda has fueled gentrification, with city databases, created by the mayor’s “innovation team,” backing them up.

Using that data, the Housing Is A Human Right report found that middle- and working-class Angelenos, particularly people of color and immigrants, were getting slammed by a citywide gentrification crisis. With that came soaring rents, record-high evictions, unwanted displacement, and a worsening homelessness emergency.

“People’s worlds were collapsing,” McDonald wrote, “and a humanitarian crisis was unfolding.”

The Housing Is A Human Right investigation is not only important for Los Angeles residents and policymakers, but also a powerful warning for the rest of the country, showing how government policies are key drivers of gentrification in American cities.

(Click here to read the award-winning investigative report.)

Follow Housing Is A Human Right on Facebook and Twitter.
Monthly Supply of Houses Still at Record Lows
By: Paul Mangione
Tags: Mortgage, Interest Rates, Housing, Real Estate, Finance

Monthly Supply of Houses in the United States stayed at record low of 3.3 months of supply in October 2020 and down from 3.6 months in July 2020 and 5.0 months in January 2020.

Comparing to 30-Year Mortgage Rates shows decreasing supply as mortgage rates decrease — the exception being the 2000–2009 period.

More detail on the 2000–2009 period below shows that two groups form above and below 5 months of supply — the 2000–2005 group and 2006–2009 group.

In 2000–2005, monthly supply remained fairly flat as mortgage rates decreased. From 2006–2009, supply increased, regardless of where rates went.

Paul Mangione

Fort Schuyler Advisors

@paul_mangione
“Zillow surfing has become a primary form of escapism for those who want to flee not just their homes but the reality of 2020.”
By: Marker Editors
Tags: Zillow, Housing, Escapism, Mortgage Rates, Real Estate

“Zillow surfing has become a primary form of escapism for those who want to flee not just their homes but the reality of 2020.” Marker Editors Nov 26, 2020·1 min read

Photo credit: jhorrocks / Getty Images

With mortgage rates at historic lows and hordes of mostly urban, stir-crazy Americans desperate for more space, The Great Housing Boom of 2020 has been one of the hottest pandemic-fueled market trends of the year — and that’s good news for Zillow. In fact, an entire digital community of aspirational home buyers, or Zillow surfers, are flocking to popular home buying sites as a form of escapism, reports Taylor Lorenz of the New York Times. “People bond over listings on Discord servers, group chats, and ‘Zillow Twitter,’” she writes, “and their obsession has made many strange and obscure listings go viral.” It sure beats doom scrolling.
Brett has a Full Buffet of Real Estate Services
By: Brett Young
Tags: Property, Housing, Success, Real Estate, Services

Being an agent for 20 years I understand what my clients want. Having a Full Buffet of real estate services is what people need when making sometimes the most important decisions in their lives is crucial.

That is why every customer and client needs a real estate agent that has been around the block a few times and understands what needs to be done in almost every instance.

Getting a transaction completed can sometimes be difficult and hard without a seasoned real estate agent helping you through that situation.

Call me I’m Brett Real Estate Agent 216–703–5740 100’s and 100’s of transactions and counting
Impact of COVID-19 on the Indian housing market
Tags: Architects, Architecture, Housing, Housing Market, Covid 19

COVID-19 is one of the biggest pandemics the world has seen in decades. It compelled the Government of India to push the whole nation into a state of lockdown in an attempt to curb the transmission of virus in the country. Unfortunately, the repeated lockdowns took a heavy toll on the economy of India and major commercial sectors saw massive downfalls in their businesses. One such sector is the Indian housing market that has experienced a massive blow during the pandemic. In fact, a report claims that the housing market in India’s top 8 cities experienced a downfall of almost 79% in the first quarter of the year 2020.

Moreover, another report by ICRA further asserts that in case the pandemic is not contained soon, it will continue to hit the nation’s economy that may adversely affect the developer’s cash flow and project delivery capabilities. Some other ways COVID-19 has impacted the Indian housing market include:

1. Home buyers have postponed their home-buying plans

Lockdown has also not only affected businesses but also resulted in millions of job losses across the country. This has eventually affected the plans of potential buyers as they remain uncertain about their job security. Thus, many people have postponed their home-buying plans for an indefinite period of time. However, the top architects in India explain that the pandemic has also made people realise the importance and value of home ownership, and with RBI announcing several rate cuts, residential real estate could experience a major boost in the post-COVID era.

2. Price of housing property has fallen in major cities

The top architects in Delhi believe that the slowdown in property demand is accentuated by the COVID-19 pandemic. For instance, a report claims that residential properties experienced a decline in prices of up to 15% in the national capital region. On the other hand, the large resale market in Delhi has experienced a massive decline of 10–15% in property prices.

3. An opportunity for Indian businesses associated with the construction business

During the pandemic, the Chinese supply lines have been largely restricted. As per the best architects in India, this can be a major boost for Indian businesses as they look forward to capitalize on the opportunity and increase their production capacities of raw materials like steel. In addition, the Government of India is also encouraging the Indian steel industry to grab a larger market share and thrust the “Make in India” campaign.

Nevertheless, things are slowly coming back on track with the Government of India and respective state governments unlocking the economy and allowing services to resume gradually. The top architectural firms in India firmly believe that things will slowly get back on track and the Indian housing market will experience an uprising in a healthier and COVID safe country.
Flats for Sale in Miyapur, Flats for Sale in Pragati Nagar, Flats for Sale in Kukatpally
By: Shashank Dar
Tags: Housing, Real Estate, Hyderabad Real Estate

Praneeth Constructions delivering 20+ perfect projects with the top-notch build quality. Are you Looking for Flats for Sale in Miyapur, Flats for Sale in Pragati Nagar, Flats for Sale in Kukatpally.

Praneeth Constructions has been established as a name for undeniable faith since its inception in 2007. Ever since, we’ve left no stone unturned in delivering 20+ projects with utmost care and detail owing to our top-notch quality. We believe the core driving factor of our victory other than our commitment to construction is the trust our patrons have kept on us. Quality is a non negotiable for us and we have derived some of the best techniques to deliver great homes for those who believe in us and share their dreams. Check out our project range and be nothing short of convinced when we say we have taken the first place to deliver to you your much awaited dream home.
An alternative to predict housing prices with Gaussian Process Regression.
By: Eric Hossein Fontes
Tags: Regression, Python, Housing, Machine Learning, Gaussian Process

It is well known that linear regression is a powerful tool for predicting housing prices, especially if the features are linearly correlated with the response variable. However, other approaches can also be used.

In this post, we will show the housing-price prediction using GPR with Matérn kernel and its differences along with a range of test_sizes. Figure 1 shows below the differences between housing-price prediction and real ones versus the living square footage since preliminary results showed that sqft_living well linearly correlates with prices.

GPR, y_test (real value), and GPR regplot versus sqft_living.

These results suggest that GPR actually fits the real housing prices quite well for low sqft_living values since, in this region, the number of data points is bigger. Moreover, the test_size 0.6 better predicted the real values in comparison with the other test_sizes. It should be noted, however, that the model predicted near-zero values.

Finally, our simple approach using GPR within the sci-kit learn package can provide useful housing-price prediction in addition to the classical linear regression approach. Still, a deeper analysis should be done in order to get the best possible insights.
Help: How It Has Many Meanings
By: Jo Ann Harris
Tags: Food, Housing, Family, Homelessness, Responsibility

They decided to call a friend that they had been close to a few years earlier and had previously worked for. They thought he would be a good resource for help or at least have some new ideas. He was an executive in the financial industry and was always full of ideas.

The friend visited and said, yes, he would help, but first he needed $100 so he could pay his mortgage. What?! The husband gives it to him leaving the wife out of that decision. Where the $100 came from in the first place was a mystery.

Anyway, it turned out later after a few months of this so called “help” they ultimately lost all of their worldly goods, mostly baby furniture, toys, clothes, etc., because this guy didn’t show up at a storage bin auction. He thought and they agreed that if he could buy their stuff or at least talk to the person that bought it they could get personal things that were needed for the babies. He agreed to do it for them.

The next day he hid all day, never came by, until the next morning and never said anything about it. Irresponsible? They had to pull it out of him about what happened. He explained that on the morning he was supposed to go he found they did not have a babysitter for his kids and he had to be there. His wife had to go to work. Or he was talked out of it by his wife and didn’t want to say so.

Because of this and lack of money and resources these folks had to move into another seedy hotel with nothing for their babies and try to start over again. He was also asked to help move them but he didn’t and left food and other items never to be seen again. After all that, he sold them a broken down car that he wanted payments on. It broke down the first week they had it. He paid for that, but it broke again soon after. Help me!
The Average Time It Takes to Sell a House and How to Speed it up
By: Brett Young
Tags: Real Estate News, Selling, Housing, Real Estate, Real Estate Investments

Selling any type of home is always about the price and about the sellers bottom line, basically how much is the seller netting out of the sell? Take a $350,000 home for sale in the Cleveland Ohio area commissions could be as high as $8,000 just to sell a home.

Priced right a home should sell quickly in today’s real estate market. I just listed a property for $259,900 and had it under contract in days. My client saved $4800 in commissions, which will go on their bottom line when the home closes. Why pay the extra money?

My Full Service Flat Fee Listing works for my clients and properties really do get closed. Being a Realtor for the last 20 years I understand that any listing a Realtor gets needs more than just adding it to the MLS. There is more marketing that needs to be done to get more potential buyers eyeballs on the property. That is why I have my own marketing company and social media outlets to get more potential buyers looking at my listings. Virtual tour and pictures also need to be added.

All the while saving clients thousands of dollars. Below is a video that gives you all the details on my Flat Fee Listing program.

Having a seasoned agent in Cleveland Ohio that understands the real estate market and has a resume to boot is priceless, and it saves you money in the process. That is called a win-win in my opinion and more importantly my clients also.

Need Real Estate done right? Call me I’m Brett 216–703–5740 Seasoned Realtor for over 20 years and I would love to get your business.
Leetcode Algorithms
By: Jen-Li Chen
Tags: Leetcode, Algorithms, JavaScript

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Leetcode : 3. Longest Substring Without Repeating Characters
Tags: Leetcode, Leetcode Solution, Algorithms, Faang, Leetcode Medium

I am an algorithmic programmer who loves to solve programming questions from various coding platforms. I am 5* at Codechef, Expert at Codeforces.
Leetcode : 2. Add Two Numbers
Tags: Leetcode, Add Two Numbers, Leetcode Solution, Algorithms, Leetcode Medium

I am an algorithmic programmer who loves to solve programming questions from various coding platforms. I am 5* at Codechef, Expert at Codeforces.
How Far Have You Gotten in Leet — (1)
By: Minho Jang
Tags: Leetcode, Leetcode Medium, Algorithms

Description

resource link : LeetCode

Explanation

The robot would be bounded in the circle if its position and direction get same with the initial while it perform the instructions in order. Expected that the robot would be heading one of the four directions - north, south, east, west- when a total order is given once. If the robot headed to the south, rotating 180 degree, then it should be back at the second repeat. If the east or the west, rotating 90 or 270 degree, then should be back at the fourth repeat at last. In other words, if the instructions repeat four times at last, we would know if the robot leaves the circle or not.

Solution

Review

I tried to solve this algorithmic way, using a queue and an array list to handle the sequential instructions, which got me in trouble. The key point of this problem is whether I was able to figure out the change of both position and direction at the same time. Dealing with it mathematically could be way easier.
LeetCode - Swap Nodes in Pairs
By: Siddhant Jain
Tags: Leetcode, Data Structure Algorithm, Recursion, Linked Lists, Competetive Programming

Problem Link: https://leetcode.com/problems/swap-nodes-in-pairs/

Problem Description: Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes. Only nodes itself may be changed.

Linked List — Data Structure

Approach Used: Recursion

Explanation: We have to readjust links of the linked list in such a way that every pair of adjacent nodes are swapped. Some things to keep in mind is that if there are at least two nodes then the new head node after all the swaps will always be the second node of the list or the next node of current head.

Now since it has to be done in pair we will always pick two nodes at a time, readjust the link and call the function again to do the same thing for rest of the nodes till we reach the base case.

The base case will be either the list is empty or has just 1 node in which case no operation can be done and we simply return the head.

Code: (Java)

public ListNode swapPairs(ListNode head) {

//base case

if(head==null || head.next==null)

return head;



//store the element we will send ahead (link to this node will be deleted in 2nd next step)

ListNode temp = head.next.next;



//new head will always be the second node of current list

ListNode newHead = head.next;



//link made from second node to first node (link to third node deleted)

head.next.next = head;



//call function again for rest of the nodes in list, first node will point to head of modified list

head.next = swapPairs(temp);



//return new head for every sublist and final original list

return newHead;

}

In case there any doubts, feel free to write it in the comments section. Thanks!
[LeetCode]#192. Word Frequency
By: Fatboy Slim
Tags: Leetcode, Bash, Leetcode Easy

Environment: bash

Key technique: cat, sort, awk

Write a bash script to calculate the frequency of each word in a text file words.txt .

For simplicity sake, you may assume:

words.txt contains only lowercase characters and space ' ' characters.

contains only lowercase characters and space characters. Each word must consist of lowercase characters only.

Words are separated by one or more whitespace characters.

Example:

Assume that words.txt has the following content:

the day is sunny the the

the sunny is is

Your script should output the following, sorted by descending frequency:

the 4

is 3

sunny 2

day 1

Solution:

cat words.txt | tr -s ' ' '

' | sort | uniq -c | sort -r | awk '{print $2, $1}'

Submissions:

Reference:

https://leetcode.com/problems/word-frequency/discuss/965775/Easy-one-liner!
[LeetCode]#193. Valid Phone Numbers
By: Fatboy Slim
Tags: Leetcode, Bash, Leetcode Easy, Regex

Environment: bash

Key technique: grep

Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bash script to print all valid phone numbers.

You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)

You may also assume each line in the text file must not contain leading or trailing white spaces.

Example:

Assume that file.txt has the following content:

987-123-4567

123 456 7890

(123) 456-7890

Your script should output the following valid phone numbers:

987-123-4567

(123) 456-7890

Analysis:

d{3}-\d{3}-\d{4}|\(\d{3} for 987–123–4567 (\d{3}\) \d{3}-\d{4} for (123) 456–7890

Solution:

\d{3}-\d{3}-\d{4}|\(\d{3}\) \d{3}-\d{4}

Submissions:

Reference:

https://leetcode.com/problems/valid-phone-numbers/discuss/843424/BASH-Easy-One-Liner
Balanced Binary Tree
By: Fellow Programmer
Tags: Leetcode, The Fellow Programmer, Java, Coding, Programming

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

Example 1:

Input: root = [3,9,20,null,null,15,7]

Output: true

Example 2:

Input: root = [1,2,2,3,3,null,null,4,4]

Output: false

Example 3:

Input: root = []

Output: true

Constraints:

The number of nodes in the tree is in the range [0, 5000] .

. -104 <= Node.val <= 104

Please visit the below blog for solution with detailed explanation:
[LeetCode]#194. Transpose File
By: Fatboy Slim
Tags: Leetcode, Bash, Leetcode Easy

Environment: bash

Key technique: while, cat

Given a text file file.txt , transpose its content.

You may assume that each row has the same number of columns and each field is separated by the ' ' character.

Example:

If file.txt has the following content:

name age

alice 21

ryan 30

Output the following:

name alice ryan

age 21 30

Solution:

NUM_FIELDS=`cat file.txt | head -1 | awk '{ print NF}'` let count=1

while [ $count -le $NUM_FIELDS ]; do

result=`cat file.txt | awk -v x=$count '{print $x}'`

echo $result let count+=1

done

Submissions:

Reference:

https://leetcode.com/problems/transpose-file/discuss/699640/awk-simple-solution
Smallest Range II
By: Fellow Programmer
Tags: Leetcode, The Fellow Programmer, Java, Coding, Programming

Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K , and add x to A[i] (only once) .

After this process, we have some array B .

Return the smallest possible difference between the maximum value of B and the minimum value of B .

Example 1:

Input: A = [1], K = 0

Output: 0

Explanation: B = [1]

Example 2:

Input: A = [0,10], K = 2

Output: 6

Explanation: B = [2,8]

Example 3:

Input: A = [1,3,6], K = 3

Output: 3

Explanation: B = [4,6,3]

Note:

1 <= A.length <= 10000 0 <= A[i] <= 10000 0 <= K <= 10000

Check below blog for solution along with detailed explanation

Follow us for more updates
LeetCode: Median of Two Sorted Arrays — JavaScript
By: Vakas Akhtar
Tags: Leetcode, Coding, JavaScript

In this article I’ll be going over a JavaScript solution to a leetcode hard question that’s asking us to find the median of two sorted arrays. The problem is as follows:

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

So for example if we were given the following inputs we should get an output that displays the median.

Input: nums1 = [1,3], nums2 = [2]

Output: 2.00000

To get to our solution the first thing I’d do is merge the two arrays. Once the arrays have been merged we can sort them. Once we have the merged array sorted we’ll be able to calculate the median.

var findMedianSortedArrays = function(nums1, nums2) {

const nums = nums1.concat(nums2)

//join the two arrays together using concat



nums.sort( function(a,b) { return a - b; } )

//sort the newly created array };

Now we can go ahead and find our median. When there’s an odd number of numbers in the sample you can simply add 1 to the total number of numbers in the sample and divide by 1 to get the median. For example if there are 5 numbers in a sample you can add 1 and divide that number by 2 to get the median 3. If there is an even amount of numbers in the sample you’d have to divide the total number of the sample by 2 and add 1. You’ll then have the two numbers in the middle of the sample that you would calculate the average of in order to find the median. So if you had a sample with 10 numbers you would have to divide by 2 which results in 5. Then add 1 to five to get the second number that is in the middle of the sample. Now you can take the average of the numbers at the 5th and 6th positions of the sample.

var findMedianSortedArrays = function(nums1, nums2) {

const nums = nums1.concat(nums2)

nums.sort( function(a,b) { return a - b; } )

if (((nums.length + 1) % 2 ) === 0){

let median = (nums.length + 1)/2

//find the index of the median in the array

return nums[median - 1]

//you need to subtract one from the index since arrays start at 0



} else {

let first = (nums.length/2)

//index of the first median

let second = first + 1

//index of the second median

let med1 = nums[first - 1]

let med2 = nums[second - 1]

const median = (med1 + med2)/2

//calculate the average of the two medians return median

}

};

Nice! Looks like our algorithm works. Now that you have an understanding of how to solve the problem I’m sure you can find a solution that’s more efficient than mine. In fact, I’ll most likely try to rework my solution and find something more efficient in the future. Thanks for reading and good luck to everyone on their leetcode grind!
LeetCode problem #33 — Search in Rotated Sorted Array (JavaScript)
By: Duncan Mcardle
Tags: Leetcode, Leetcode Solution, JavaScript, Leetcode Medium, Javascript Development

In this LeetCode problem, we’re given an array of numbers, and a target number, and asked to find the target number in the array (or return -1 if it cannot be found). As an added complexity, the array is in ascending order, but not from start to finish. Instead, the pivot point (the point at which the ordering “resets”) is unknown.

This complication is billed as a “rotated sorted array”, and what it basically means is that a sorted array of [1, 2, 3, 4, 5] has been “rotated” or pivoted at a random point, meaning you might be given [3, 4, 5, 1, 2] or [5, 1, 2, 3, 4] .

The reason this complexity matters is that a standard binary search will no longer work, because after slicing the array in two, you cannot simply say “is the target in the left or right side” in the traditional “greater than array[left] and less than array[middle]” as you would for a normal binary search.

Solution #1: An adjusted binary search

In reality, the solution is not that different to a normal binary search; we simply have to accommodate the complexity. This is handled by adding an extra step to the aforementioned logic, which becomes “Is the left-hand side ordered? If yes, is the target greater than or equal to array[left] and less than array[middle] (AKA on the left side)? If no, is the target greater than or equal to array[middle] (AKA on the right side)?”.

This is because once you pivot or rotate an array at a single point, half of the array will still be ordered in a standard ascending fashion, meaning we can still apply the same logic to that side, and by doing so, identify which side the number belongs to.

So what exactly are we doing here? Well in simple terms, we’re repeatedly diving the array of numbers in 2, and looking at each side to see if it contains our target number. We continue this process until we find our target number, either because we find it at the middle point, or because we get down to our last available number, at which point we’ve either found the target, or can safely say that the target was not present in the array.

Solution #2: Cheat

If, like me, you saw this question and thought “isn’t that incredibly simply?”, you’d be right. A standard brute force approach would simply be to loop through all numbers in the array, looking for the target, like so:

Even better, we can use JavaScript’s built-in indexOf() method, which not only finds a value in an array, but even returns the correct response ( -1 ) if the value can’t be found.

But both of these solutions require every value in the array to be checked, which of course makes them inefficient. By splitting our array in the earlier outlined binary search method, we reduce the number of checks required dramatically. Additionally, as we are using our own code and not built-in functionality (such as with indexOf() ), we can assume that the performance of our approach will remain roughly unchanged between browsers and browser versions.
[LeetCode]#195. Tenth Line
By: Fatboy Slim
Tags: Leetcode, Bash, Leetcode Easy, Bash Script

Environment: bash

Key technique: sed

Given a text file file.txt , print just the 10th line of the file.

Example:

Assume that file.txt has the following content:

Line 1

Line 2

Line 3

Line 4

Line 5

Line 6

Line 7

Line 8

Line 9

Line 10

Your script should output the tenth line, which is:

Line 10

Solution:

sed -n '10p' file.txt

Submissions:
367 days of code
By: Roman Stremedlovskyi
Tags: Leetcode, Education, Engineering

Be yourself; everyone else is already taken.
Two Sum
By: Jack Tawil
Tags: Leetcode, Algorithms, JavaScript, Coding, Development

Brute Force

With brute force, we try every possible combination of numbers and aren’t particularly worried about runtime. It’s important to first just get a working solution and then optimize.

First we must set an empty array that we can later store our answers in. Within a double for loop, we use indexes i and j to get values within our array and see if they add up to the target sum value. If so, we push it to our answers array. Lastly, we return answers .

Looking at this in terms of runtime, this is probably the worst solution we could create — O(n²).
[LeetCode]#1688. Count of Matches in Tournament
By: Fatboy Slim
Tags: Leetcode, Leetcode Easy, Python, Logic, Python3

Environment: Python 3.7

Key technique: logic

You are given an integer n , the number of teams in a tournament that has strange rules:

If the current number of teams is even , each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.

, each team gets paired with another team. A total of matches are played, and teams advance to the next round. If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round.

Return the number of matches played in the tournament until a winner is decided.

Example 1:

Input: n = 7

Output: 6

Explanation: Details of the tournament:

- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.

- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.

- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.

Total number of matches = 3 + 2 + 1 = 6.

Example 2:

Input: n = 14

Output: 13

Explanation: Details of the tournament:

- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.

- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.

- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.

- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.

Total number of matches = 7 + 3 + 2 + 1 = 13.

Analysis:

n team will get (n-1) matches in examples in Ex 1 and Ex 2. Namely, we can output as answer.

Solution:

class Solution:

def numberOfMatches(self, n: int) -> int:

return n-1

Submissions:
Valid Parentheses
Tags: Leetcode, Valid Parentheses, Leetcode Easy

My Solution

const isValid = (s) => {

const pair = {

"(": 1,

")": -1,

"{": 2,

"}": -2,

"[": 3,

"]": -3,

};

if (s.length % 2 !== 0) return false;

let checkNum = 0;

let checkArr = [];

for (symbol of s) {

checkNum += pair[symbol];

checkArr.push(pair[symbol]);

}

if (checkNum !== 0) return false;

let halfCheck = [];

const half = checkArr.length / 2;

for (i = 0; i < half; i++) {

if (checkArr[half - 1 - i] + checkArr[half + i] !== 0) {

halfCheck = [...halfCheck, checkArr[half - 1 - i], checkArr[half + i]];

}

}

if (halfCheck.length === 0) return true;

const remainder = checkArr.filter(

(el, idx) => el + checkArr[idx + 1] !== 0 && el + checkArr[idx - 1] !== 0

);

return remainder.length === 0;

};

This is my first trial. my idea comes from converting parenthesis to number. it works well with the normal case, but it didn’t considered ordering such as }{ , ][ , )( .

const isValid = (s) => {

if (s === null || s.length <= 0) return true;

const cArr = s.split("");

let stack = [];

for (c of cArr) {

if (c === "[") stack.push("]");

else if (c === "{") stack.push("}");

else if (c === "(") stack.push(")");

else if (stack.length === 0 || c !== stack.pop()) return false;

}

if (stack.length === 0) return true;

return false;

};

This is my second solution. way better simple and works well.
LeetCode 刷題紀錄 ｜167. Two Sum II — Input array is sorted (Easy)
By: Roy Wang
Tags: Leetcode, Data Structures, Algorithms, JavaScript, Coding

這題是 Two Sum 的變形題，他假設輸入的數列會是已經排列好的

Two Sum II — Input array is sorted

Question

Link: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

Your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Example 1:

Input: numbers = [2,7,11,15], target = 9

Output: [1,2]

Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

Example 2:

Input: numbers = [2,3,4], target = 6

Output: [1,3]

Example 3:

Input: numbers = [-1,0], target = -1

Output: [1,2]

Constraints:

2 <= nums.length <= 3 * 104

-1000 <= nums[i] <= 1000

nums is sorted in increasing order .

is sorted in . -1000 <= target <= 1000

Answers

這題要學怎麼善用數列已由小到大排列的特性

Solution 1: Two Pointers

想法

我們可以用兩個指針分別指向第一個元素(指針low)跟最後一個數字(指針high) 比較兩個數字： 當兩個數字的和相等於目標數時，我們就找到了題目的唯一解 如果數字和小於目標，把指著第一個數字的指針 low 往後走，使數字和變大 如果數字和大於目標，把指著最後一個數字的指針 high 往前走，使數字和變小 一直重複到找到解為止

用範例實際走一遍

假設 input array: nums = [1, 2, 3, 4, 7], 目標 target = 6

起始 low = 0, high = nums.length — 1

當 low < high 時，sum = nums[low] + nums[high]

low = 0 < high = 4, sum = 1 + 7 = 8 , 8 > 6，所以把high的指針往前移動, high -=1

low = 0 < high = 3, sum = 1 + 4 = 5, 5 < 6，所以把low往後移動, low += 1

low = 1 < high = 3, sum = 2 + 4 =6, 6 = 6, 找到唯一解, 此時 return [low+1, high + 1] 因為要回傳第幾個數字

ans = [2, 4]

Javascript 程式碼如下



var twoSum = function(nums, target) {

let low = 0;

let high = nums.length - 1;



while (low < high) {

let sum = nums[low] + nums[high];

if (sum === target) {

return [low + 1, high + 1];

} else if (sum < target) {

low++;

} else {

high--;

}

}



return [-1, -1];

};

複雜度

Time complexity: O(n), n個元素最多只會被造訪1次

Space complexity: O(1), 只用到兩個指針

Python 程式碼

class Solution:

def twoSum(self, numbers: List[int], target: int) -> List[int]:

start = 0

end = len(numbers) - 1

res = []

while start < end:

sum = numbers[start] + numbers[end]

if target > sum:

start+=1

elif target < sum:

end-=1

else:

return [start + 1, end + 1]

Reference:
LeetCode Top Interview Questions — Easy Collection (Strings)
By: Minal Vaity
Tags: Leetcode, Tech, Java, Coding, Programming

1) Reverse String

Write a function that reverses a string. The input string is given as an array of characters char[] .

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

String Reverse Java Solution

Input: [“h”,”e”,”l”,”l”,”o”] Output: [“o”,”l”,”l”,”e”,”h”]

2) Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Reverse Integer Java Solution

Input: x = 123 Output: 321

3) Valid Anagram

Given two strings s and t , write a function to determine if t is an anagram of s.

Valid Anagram Java Solution

Input: s = “listen”, t = “silent” Output: Is Anagram? True

4) Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Valid Palindrome Java Solution

Input: “A man, a plan, a canal: Panama” Output: true

5) String to Integer (atoi)

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

String to Integer (atoi) Java Solution
[LeetCode] Missing Number
By: Trevor Low
Tags: Leetcode, Algorithms, JavaScript

Problem

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.

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

Input: nums = [3,0,1]

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. Input: nums = [0,1]

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. Input: nums = [9,6,4,2,3,5,7,0,1]

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. Input: nums = [0]

Output: 1

Explanation: n = 1 since there is 1 number, so all numbers are in the range [0,1]. 1 is the missing number in the range since it does not appear in nums.

My Approach

I’m always surprised at how much knowledge I retained from my math and engineering classes. In this problem I immediately recognized that Gauss’s formula could be implemented to create a simple and succinct solution. Gauss’s formula tells us the sum of all numbers in a sequence, if that sequence contains all the numbers in a set. Below was my pseudo code as I approached the problem.

// Gauss’s formula to get the intended sum of all the numbers in the set. If the set is [N…M] and the number of elements is T, then the sum of the sequence is sum = (T/2)*(M+N). Using this I can set a target sum which we are trying to aim for and compare it to the actual sum of the array.

// sum all the numbers in the array

//subtract the two and that is the number.

//edge case is zero, check for zero. If not then return 0.

//check for zero by the length of the array being equal to the sum.

//edge case arr.length = 1, check if 0 is in it if not return 1, check if 0 is in it, if not return 0.

Solution

function missingNumber(arr){ let length = arr.length; let target = (length/2)*(length + 1) let sum = 0; for(let i = 0; i<length; i++){ sum += arr[i] } if(target !== sum && length !== 0){ return target - sum } if(length === 0 && arr[0]===0){ return 1 }else{ return 0 } }

Big O

Time is O(n) because we must iterate through each element of the array.

Space is O(1), constant space because memory allocation remains constant with input.
Leetcode SQL
By: Jen-Li Chen
Tags: Leetcode, Sql, Solutions

Leetcode SQL

184. Department Highest Salary

The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id.

+----+-------+--------+--------------+

| Id | Name | Salary | DepartmentId |

+----+-------+--------+--------------+

| 1 | Joe | 70000 | 1 |

| 2 | Jim | 90000 | 1 |

| 3 | Henry | 80000 | 2 |

| 4 | Sam | 60000 | 2 |

| 5 | Max | 90000 | 1 |

+----+-------+--------+--------------+

The Department table holds all departments of the company.

+----+----------+

| Id | Name |

+----+----------+

| 1 | IT |

| 2 | Sales |

+----+----------+

Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, your SQL query should return the following rows (order of rows does not matter).

+------------+----------+--------+

| Department | Employee | Salary |

+------------+----------+--------+

| IT | Max | 90000 |

| IT | Jim | 90000 |

| Sales | Henry | 80000 |

+------------+----------+--------+

Explanation:

Max and Jim both have the highest salary in the IT department and Henry has the highest salary in the Sales department.

Solution:

select d.Name as Department,

e.Name as Employee,

Salary

from Department d

join Employee e

on d.Id = e.DepartmentId

where (e.Salary, e.DepartmentId) in

(select max(Salary), DepartmentId from

Employee group by 2)

;

Link
102. Binary Tree Level Order Traversal Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level). For example: Given binary tree…
By: Jen-Li Chen
Tags: Leetcode, Algorithms, JavaScript

Leetcode Algorithm

102. Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:

Given binary tree [3,9,20,null,null,15,7] ,

3

/ \

9 20

/ \

15 7

return its level order traversal as:

[

[3],

[9,20],

[15,7]

]

Solution:

// create a result array, a queue array and a row array.

// queue.push() and queue.shift() var levelOrder = function(root) { let result = []; if (root === null) return result; // return an empty array

let queue = [];

queue.push(root); while (queue.length > 0){ let row = []; let rowSize = queue.length; while (rowSize > 0){ let currentNode = queue.shift(); if (currentNode.left !== null){ queue.push(currentNode.left);

} if (currentNode.right !== null){ queue.push(currentNode.right);

} // put the nodes in the queue to the row

row.push(currentNode.val);

rowSize --; }

result.push(row); }

return result;

};



Link
Validate Binary Search Tree
By: Fellow Programmer
Tags: Leetcode, The Fellow Programmer, Java, Coding, Programming

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node’s key.

the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key.

the node’s key. Both the left and right subtrees must also be binary search trees.

Example 1:

Input: root = [2,1,3]

Output: true

Example 2:

Input: root = [5,1,4,null,null,3,6]

Output: false

Explanation: The root node's value is 5 but its right child's value is 4.

Constraints:

The number of nodes in the tree is in the range [1, 104] .

. -231 <= Node.val <= 231 - 1

Check out below for solution with detailed explanation
Lemonade Change — LeetCode
By: Soren Rood
Tags: Leetcode, Leetcode Easy, Data Structures, Algorithms, Computer Science Student

This one stumped me at the beginning until I figured out I had to keep track of the bills. Once you start keeping track of bills, you just add cases and loop through the entire list until you are done.

Here’s the problem:

LeetCode #806

Here’s my solution to this:

https://carbon.now.sh

Something I just realized is that we can actually remove line 5, since we don’t need to keep track of the 20’s at all.

Here’s the submission report for the above code:

Faster than 82%

As usual my source code is located here and my social links are located here.
[Leet Code] Countings bits
By: Matthew Boyd
Tags: Leetcode, Data Structures, Algorithms, Leetcode Solution, Leetcode Medium

Leetcode: https://leetcode.com/problems/counting-bits/

Problem:

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.

Example 1:

Input: 2

Output: [0,1,1]

Example 2:

Input: 5

Output: [0,1,1,2,1,2]

Solution:

class Solution(object):

def countBits(self, num):

"""

:type num: int

:rtype: List[int]

"""

answer = []

for i in range(num+1):

binAnswer = list((format(i, "b")))

answer.append(binAnswer.count("1"))

return answer

Explanation:
Leetcode: Sort Colors Python Solution
By: Celine Surai
Tags: Leetcode, Python, Software Development, Software Engineering, Coding Interviews

Photo by Hitesh Choudhary on Unsplash

The Question:

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

Here, we will use the integers 0 , 1 , and 2 to represent the color red, white, and blue respectively.

We are given a follow up and told to solve this problem without using the library’s sort function and also whether we can up with a one-pass algorithm using only 0(1) constant space.

Here is an example of how the output should look like once solved

Input: nums = [2,0,2,1,1,0]

Output: [0,0,1,1,2,2]

This is a leetcode medium level question.common during coding interviews as well! See, the obvious or rather straightforward solution here would be using a counting sort whereby, you first iterate the array counting the numbers of zeros,ones, and twos and then overwriting the array with the total number of zeros,ones and followed by twos. However this solution has a space limitation. It’s space complexity is 0(n) which means it will be need more space should the array be bigger. Hence the reason why we are being asked whether we can come up with a one-pass algorithm using only constant-space

The Solution:

The most optimal way of solving this would be to divide the array into three parts and have a left pointer, current pointer, and right pointer.

Then we will iterate the array and check whether the current pointer is equals to zero and if it is equal we get to swap with the left pointer, at the same time incrementing our current and left pointer.

We also check whether the current pointer is equals to two whereby if it is equal we go ahead and swap the current pointer with the right pointer while decrementing the right.

We will keep doing this until the current pointer is less than or equals to the right pointer. After this is done, our array will get sorted.

Here is the solution in Code:

Sort Colors

And there you go! We have solved the problem in constant space using a one pass algorithm. I hope that this article serves to give you a picture of how to approach this problem during coding interviews. For a more detailed description watch how I solve the problem on my channel.

See you on the next coding problem!