# Roman to Integer

Roman numerals are represented by seven different symbols: IVXLCD and M.

Symbol                Value

I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, 2 is written as II in Roman numeral, just two one’s added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

• I can be placed before V (5) and X (10) to make 4 and 9.
• X can be placed before L (50) and C (100) to make 40 and 90.
• C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.

Example 1:

Input:

 s = "III"


Output:

 3


Example 2:

Input:

 s = "IV"


Output:

 4


Example 3:

Input:

 s = "IX"


Output:

 9


Example 4:

Input:

 s = "LVIII"


Output:

 58


Explanation:

 L = 50, V= 5, III = 3.


Example 5:

Input:

 s = "MCMXCIV"


Output:

 1994


Explanation:

 M = 1000, CM = 900, XC = 90 and IV = 4.


Constraints:

• 1 <= s.length <= 15
• s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
• It is guaranteed that s is a valid roman numeral in the range [1, 3999].

This problem was taken from Leetcode Roman To Integer

## Solution

Solution 1: Left to right pass

/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
var len = s.length;
var i = 0;
var map = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
var sum = 0;
while(i < len) {
var currentVal = map[ s[i] ];
var nextVal = map[ s[i + 1] ];
if( currentVal < nextVal) {
sum += nextVal - currentVal;
i ++;
}
else {
sum += currentVal;
}
i ++;
}
return sum;
};

Solution 2: Left to right (or right to left) pass improved

/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
var len = s.length;
var i = 0;
var map = {
'I': 1,
'IV': 4,
'V': 5,
'IX': 9,
'X': 10,
'XL': 40,
'L': 50,
'XC': 90,
'C': 100,
'CD': 400,
'D': 500,
'CM': 900,
'M': 1000
}
var sum = 0;
while(i < len) {
var currentVal = map[ s[i] ];
var nextVal = map[ s[i + 1] ];
if( currentVal < nextVal) {
var sumbol = s[i] + s[i+1];
sum += map[sumbol];
i ++;
}
else {
sum += currentVal;
}
i ++;
}
return sum;
};

Solution3: Right to left pass

In the “subtraction” cases, such as XC, we’ve been updating our running sum as follows:

sum += value(C) - value(X)


However, notice that this is mathematically equivalent to the following:

sum += value(C)
sum -= value(X)


Utilizing this means that we can process one symbol each time we go around the main loop. We still need to determine whether or not our current symbol should be added or subtracted by looking at the neighbour though.

This way we could start from the most right symbol an initialize the sym with it, since every most right symbol will always be added to the sum.

/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
var len = s.length;
var i = len - 1;
var map = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
var sum = map[ s[i] ];
i --;
while(i > -1) {
var currentVal = map[ s[i] ];
var prevVal = map[ s[i + 1] ];
if( currentVal < prevVal) {
sum -= currentVal;
}
else {
sum += currentVal;
}
i --;
}
return sum;
};

# Container With Most Water

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai)n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.

Notice that you may not slant the container.

Example 1:

Input:

 height = [1,8,6,2,5,4,8,3,7]


Output:

 49


Explanation:

 The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.


Example 2:

Input:

 height = [1,1]


Output:

 1


Example 3:

Input:

 height = [4,3,2,1,4]


Output:

 16


Example 4:

Input:

 height = [1,2,1]


Output:

 2

This problem was taken from Leetcode Container With Most Water

## Solution

A better than brute force solution is to use a variation of “sliding doors” algorithm.

Let’s consider this case: [1,3,4,3]. The area with most water will be the one with highest height and length.

To find it we set up two pointers: one at position 0, and one at the end of the array. The amount of water that could be collected here is min(leftPointerValue, rightPointerValue) * length,
where length is rightPointer – leftPointer. Which is 4.

Now it’s clear that if rightPointerValue > leftPointerValue there is no point of keep moving rightPointer because we won’t get any bigger amount of water since it will always be limited by the leftPointerValue (height) and the length will always be smaller than the previous length.

So in this case we will move the leftPointer forward to evaluate the next case.

Here the amount of the water collected is min(leftPointerValue, rightPointerValue) * length which is min(3, 3) * 3 = 9.

Nex we continue evaluating all cases till leftPointer = rightPointer (length = 0), and we didn’t find bigger amount of water collected, so the answer we found on the second evaluation is the right answer: 9.

/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function(height) {

var maxArea = 0;
var pLeft = 0;
var pRight = height.length - 1;
var len = pRight - pLeft;

while(len > 0) {
var pLeftVal = height[pLeft];
var pRightVal = height[pRight];

if(pLeftVal > pRightVal) {
maxArea = Math.max( len * pRightVal, maxArea );
pRight --;
}
else {
maxArea = Math.max( len * pLeftVal, maxArea );
pLeft ++;
}
len --;
}
return maxArea;
};

var height = [1,8,6,2,5,4,8,3,7];
console.log( maxArea(height) );

# The scenario

– Let’s imagine that you have a card component that you could show and hide with a button.
– When the component become visible an asynchronous function is called to get current time.
– Once the fetch is done, it will update the card showing current time.

# The problem

– Let’s say that this asynchronous function is taking a few seconds to bring data back, and before it finishes the user decides to hide (or more appropriate thing to use is unmount) the card by clicking the button.
– when fetch is done, the asynchronous function will call setState to update the component that is no longer there and you will receive the nasty warning telling you that React can’t perform a React state update on an unmounted component.

And it makes perfect sense since the component and it’s DOM is not there any more.

# The solution

– Use React refs to determine if the component is mounted or not.

./App.js

import "./styles.css";
import Card from "./card";
import React, { useState } from "react";

export default function App() {
const [cardVisible, setCardVisible] = useState(true);
const [buttonText, setButtonText] = useState("Hide card");

const setVisibility = () => {
setButtonText(buttonText === "Show card" ? "Hide card" : "Show card");
setCardVisible(!cardVisible);
};

return (
<div className="App">
<button onClick={setVisibility}>{buttonText}</button>
{cardVisible && <Card />}
</div>
);
}


./card.js

import React, { useEffect, useRef, useState } from "react";

const card = () => {
const mounted = useRef(false);

async function fetchData() {
console.log("fetchData called!");
fetch(
"https://www.toni-develops.com/external-files/examples/service-workers/delayed-response.php"
).then((response) => {
response.text().then(function (text) {
console.log(">>>", mounted.current);
if (mounted.current === null) return;
console.log("Fetch response is available!");
setData(text);
});
});
}

useEffect(() => {
fetchData();
});

return (
<div ref={mounted} className="card">
<p>{data}</p>
</div>
);
};

export default card;

what we just did:

– Line 5 – we added mounted param which is a reference to any DOM object in this component. If the component is not mounted mounted.current will return null
– Line 26 – we just add the actually reference tag to any DOM object that is constantly visible in our component. In most cases this is just the card wrapping div.
– Line 14 – we just check if the component exist or not before performing stateUpdate

Obviously we could also use the old fashion DOM way and use querySelector to check if the element is actually there but I guess useRefs is the more “React way” of doing this.

The entire example could be seen here:

# Install SonarQube

Instructions

Install SonarQube. This is a reporting tool.

$brew install sonar But it also requires Sonar-scanner in order to scan the code. $ brew install sonar-scanner

# Install Jest Sonar reporter

Jest sonar reporter is a plug-in that wi
jest-sonar-reporter is a custom results processor for Jest. The processor converts Jest’s output into Sonar’s generic test data format.

In other words we need this in order for SonarQube to to be able to process the result of Jest tests.

$yarn add jest-sonar-reporter --dev Let’s configure jest to use sonar-reporter and also to process and exclude of testing certain folders: ./package.json ... "jest": { "setupFiles": [ "./src/setupTests.js" ], "collectCoverageFrom": [ "**/*.{js,jsx}", "!coverage/**", "!node_modules/**", "!src/index.js", "!src/setupTests.js", "!public/**", "!server-build/**" ], "moduleNameMapper": { "\\.(css|less|scss)$": "<rootDir>/src/__mocks__/styleMock.js"
},
"coverageDirectory": "reports/coverage",
"coverageReporters": [
"json",
"lcov",
"text"
],
"testResultsProcessor": "jest-sonar-reporter"
},
"jestSonar": {
"reportPath": "reports",
"reportFile": "test-reporter.xml"
},
...
what we just did:
– lines 6 -14 we described which folders to be added in the coverage (“**/*.{js,jsx}”) and which to be excluded. (All that start with exclamation mark).
– line 18 describes where to create the report file, which sonarqube scanner will use.

This file is used to configure sonnar-scanenr.

./sonar-project.properties

sonar.projectKey="SparkJS-key"
sonar.projectName="SparkJS"
sonar.sourceEncoding=UTF-8
sonar.sources="./src"
sonar.tests="./src"
sonar.exclusions=**/*.test.js
sonar.test.inclusions=**/*.test.js
sonar.javascript.lcov.reportPaths=reports/coverage/lcov.info
sonar.testExecutionReportPaths=reports/test-reporter.xml

what we just did:
projectKey – is the unique identifier of the project.
projectName – is the name of the project.
sources – describes which folders to scan
tests – where the scanner will look for test files.
exclusions – which files should be excluded from coverage.

# Create SonarQube project

Run sonar-scanner inside the root of the project:

$sonar-scanner Navigate to SonarQube web UI at the projects section, and you will see the new project created. # Integrating SonarQube quality tests with Jenkins Before you continue make sure that you have Jenkins installed locally and is configured to run tests and deploy your project. Detailed instructions are found here: Adding continuous integration with Jenkins pipeline and Github webhooks After you have Jenkins set up and configured, we could proceed to adding another two stages into the pipeline: – Running SonarQube Scanner Quality Gate ## Adding SonarQube plug-in for Jenkins Open Jenkins Web UI ->Manage Jenkins->Manage Plugins and add ‘SonarQube Scanner for Jenkins ## Configuring Jenkins pipeline to runs Sonar-scanner and do Quality gate. Open ./jenkins/pr.groovy pipeline { agent any tools {nodejs "SparkJS"} stages { stage('Cloning Git Repo') { steps { git 'https://github.com/ToniNichev/projects-sparkjs.git' } } stage('Install dependencies') { steps { echo '#################################' echo 'Building...' echo '#################################' sh '/usr/local/bin/yarn install' } } stage('Running Tests') { steps { echo '#################################' echo 'Running tests ...' echo '#################################' sh '/usr/local/bin/yarn test' } } stage('Running ESLint') { steps { echo '#################################' echo 'Running ESLint ...' echo '#################################' sh '/usr/local/bin/yarn lint' } } stage('Running SonarQube Scanner') { steps { script { // requires SonarQube Scanner 2.8+ scannerHome = tool 'SonarScanner' } withSonarQubeEnv('Tonis SonarQube') { // If you have configured more than one global server connection, you can specify its name sh "${scannerHome}/bin/sonar-scanner"
}
}
}

// No need to occupy a node
stage("Quality Gate"){
steps {
script {
timeout(time: 2, unit: 'MINUTES') { // Just in case something goes wrong, pipeline will be killed after a timeout
def qg = waitForQualityGate() // Reuse taskId previously collected by withSonarQubeEnv
if (qg.status != 'OK') {
error "Pipeline aborted due to quality gate failure: ${qg.status}" } } } } } stage('Deploy and run server') { steps { echo 'Starting server ...' sh '/usr/local/bin/yarn clean; /usr/local/bin/yarn build-prod; /usr/local/bin/yarn build-prod-ssr;' sh '/usr/local/bin/pm2 start ./server-build/server-bundle.js -f' } } } } Now make some code changes like for example ./env.production change the app name title i.e. APP_NAME=Webpack React Tutorial Production 2 Push your changes and navigate back to Jenkins WEB UI. Now two new steps will be added to the pipeline:”Running SonarQube Scanner”and”Quality Gate” # Working with danger JS and integrating it with GitHub Table of Contents # What is danger JS ? Danger runs during your CI process, and gives teams the chance to automate common code review chores. It’s an automation checker against any opened pull requests. # Install danger JS Navigate to the root of your folder and execute: $ yarn add danger --dev; yarn danger init

yarn danger init
yarn run v1.22.4

# Create pull request and test danger JS locally

Before we could do this, we have to export environment variable DANGER_GITHUB_API_TOKEN with the value equal to the tocen that we created in the previous chapter.

$export DANGER_GITHUB_API_TOKEN="XXXXXXXXXXXXXXXXXXXXXXXX" And now, test it locally: $ yarn danger pr https://github.com/ToniNichev/projects-sparkjs/pull/1

# Integrate it with GitHub

Github provides api that we could use to get information about commits and pull requests.

Example of getting all pull requests:

https://api.github.com/repos/ToniNichev/projects-sparkjs/pulls?state=all

Before we are able to see messages in github we have to txport two more environment variables:

$export DANGER_FAKE_CI="YEP"$ export DANGER_TEST_REPO='ToniNichev/projects-sparkjs'

Test danger JS. Execute:

\$ DANGER_TEST_PR='4' yarn danger ci

And if everything is correct you should see the messages in the pull request:

# Adding continuous integration with Jenkins pipeline and Github webhooks

Pre requirements:

• Windows, Linux or OSX machine running latest Java JDK or JRE.
• Github account
• You could fork the example project repo or you could use project of your own if you prefer.
• if you want to set up a Webhook that will trigger automatic builds  you will need Jenkins to be accessible from outside your network. You will have to set up port forwarding in your rauther.

Example project repo:

branch-name:
Click To Copy

# Installing Jenkins

Jenkins come in two versions: Long-term Support (LTS) and Weekly releases. If you want stable version choose (LTS)

Jenkins also require Java so make sure that you have the appropriate version installed. By the time I’m writing this it requires

• On MAC OS
brew install jenkins-lts

• On CentOS
sudo rpm --import https://jenkins-ci.org/redhat/jenkins-ci.org.key
then install it.
yum install jenkins
Then start the service
brew services start jenkins-lts

## Change default port (if needed, homebrew only)

Jenkins runs by default on port 8080, but I have another app running there so I had to change the default port.

Edit homebrew plist file as follows:
(replace 2.222.1 with the actual installed version)

/usr/local/Cellar/jenkins-lts/2.222.1/homebrew.mxcl.jenkins-lts.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>homebrew.mxcl.jenkins-lts</string>
<key>ProgramArguments</key>
<array>
<string>/usr/libexec/java_home</string>
<string>-v</string>
<string>1.8</string>
<string>--exec</string>
<string>java</string>
<string>-Dmail.smtp.starttls.enable=true</string>
<string>-jar</string>
<string>/usr/local/opt/jenkins-lts/libexec/jenkins.war</string>
<string>--httpPort=8082</string>
</array>
<true/>
</dict>
</plist>



Line 18: change the port to 8082.
Line 17: Change  httpListenAddress from 127.0.0.1 to 0.0.0.0. This is necessary if you want to access Jenkins from Internet, outside of the internal network.

Now run the server as service.

brew services start jenkins-lts

## Install the necessary plug-ins

Jenkins -> Manage Jenkinst -> Manage Plugins

# Create First Pipeline

## Create New Item

Pipeline ->Pipeline Script From SCM and put Git repository link.

## Create Jenkins file with the pipeline steps

The whole pipeline should be wrapped in

pipeline {
}

A few words about pipeline syntax:

Agent is declared in the very beginning of the pipeline. This instructs Jenkins to allocate an executor (on a node) and workspace for the entire Pipeline.
An agent is typically a machine, or container, which connects to a Jenkins master and executes tasks when directed by the master.

Stage is part of Pipeline, and used for defining a conceptually distinct subset of the entire Pipeline, for example: “Build”, “Test”, and “Deploy”, which is used by many plugins to visualize or present Jenkins Pipeline status/progress.

Step A single task; fundamentally steps tell Jenkins what to do inside of a Pipeline or Project.

Full glossary could be found here

Let’s get started by creating pipeline file in the example project folder:

./jenkins/pr.groovy

pipeline {
agent any

tools {nodejs "SparkJS"}

stages {

stage('Cloning Git Repo') {
steps {
git 'https://github.com/ToniNichev/projects-sparkjs.git'
}
}
stage('Install dependencies') {
steps {
echo '######################'
echo 'Building...'
echo '######################'
sh '/usr/local/bin/yarn install'
}
}

stage('Running Tests') {
steps {
echo '######################'
echo 'Running tests ...'
echo '######################'
sh '/usr/local/bin/yarn test'
}
}
}

post {
always {
echo 'Starting server ...'
sh '/usr/local/bin/yarn clean; /usr/local/bin/yarn build-prod; /usr/local/bin/yarn build-prod-ssr;'
sh '/usr/local/bin/pm2 start ./server-build/server-bundle.js -f'
}
}
}


what we just did:
– line 2, told Jenkins that it could run this pipeline for any agent. Agent basically allows you to specify where the task is to be executed. It could be Docker, Node or any agent.
– line 6, we defined our stages: Cloning Git Repo, Install dependencies, Running Tests
– line 32: finally after all stage script passed we defined the post script to run the server.

I’m using pm2 (a process manager and launcher) for running the app so if you don’t have it installed you should install it using npm or yarn.

npm install pm2@latest -g

or

yarn global add pm2

So now everything is set up, let’s test the pipeline. Navigate to the pipeline and  from the vertical menu on the right select “build now”. If everything is good you should see a pipeline stages with progress bars filling out.

After the execution you could navigate to the log (build history in the right side -> select last job ->Console output)

There you could see a log of all stages executions including the snapshot tests

Test Suites: 2 passed, 2 total

# Setting up Jenkins to listen to Github Webhook and trigger automatic builds on every commit

This is probably the best and the most tricky one to make it work. We are going to add Github Webhook that will make a post request to Jenkins every time when we push code change and this will trigger our pipeline and will rebuild the app and redeploy it. We are building so called continuous integration process. CI

Select the current (admin) user from the top right.

then on the left vertical menu choose “configure”.
Navigate to the “API Token” section and click “Add new token”

Important!!! Copy the token and save it somewhere safely because you won’t be able to see it again.

Navigate back to the pipeline that we created and click “configure” from the left vertical menu.
Scroll down to “Build Triggers” and check “Trigger builds remotely (e.g., from scripts)”

Paste the authentication token in the field and copy the example url below the text field where it says: “Use the following URL to trigger build remotely” We will need this to add it into Github webhook.

Click “save” on the bottom.

# Setting up Github Webhook

Navigate to the example project in your Github space, select “settings” and “Webhooks”.

Click on “add webhook” and you will see this screen:

In the payload URL put the url that we copied from Jenkins -> Build Triggers above.

Important!!! Make sure that you replace ‘JENKINS_URL’ with the actual IP of the machine where Jenkins is running or the hostname if you set up one, and replace the token with the actual token that we generated for the ‘admin’ user.

On the dropdown below “Content type” select “application/json”

Leave “Secret” below empty.

Next on “Which events would like to trigger this webhook” is up to you, but for simplicity I just left the default “Just push event”

Make sure that “Active” is checked and click “Add webhook”

At this point if you commit some changes to the example project and push them a webhook should fire and do a POST request to your jenkins instance, notifying it that there are code changes and triggering the pipeline process … but when I did this and looked at the response I saw: “403 No valid crumb was included in the request

This simply means that Jenkins require another token to be sent in the headers, to make sure that only authorised cities (Github in this example) will trigger the pipeline process.

This is the most obscure and unclear part of setting up Webhooks. I google it for quite some time and figured out that there is no way to send custom header parameters (like Jenkins-crumb) from Github so the only option was to disable this security feature … which I think is fine since the pipeline is already protected with API key that we added.

# Disabling CSRF Protection in Jenkins

The CSRF protection settings lives in “Manage Jenkins” under “Configure Global Security” but as it looks like the lates Jenkins releases don’t have an option to disable this, so the only alternative was to do it through the groovy script.

Go to Manage Jenkins -> Script Console
and paste the code below in the console.

import jenkins.model.Jenkins
def instance = Jenkins.instance
instance.setCrumbIssuer(null)

Click run. You will see empty result which is expected.

Go to the example project commit some change and push it again.

git commit . -m"Testing push webhook";git push

Navigate to Jenkins and you will observe that the new tack is queued in the “Build executor status” in the bottom left.

# Test it

Let’s do it again by making some code changes and commit and push and observe how Jenkins will run the pipeline, test and deploy the project!

Cheers!

# Using Nginx as a reverse proxy and add source code replacement

I have web app (in my case Node app running on port 3000)
I would add Nginx in front of it and will serve it on port 80.

Find Nginx.config file by executing: nginx -V

Edit nginx.conf and edit the server section

...
server {
listen       8081;
server_name  toni-develops.com;
location / {
proxy_pass http://localhost:3000/;
}
...

Line 5 tells enginx to intercept all requests / and proxy them from http://localhost:3000
If the request from example is /home Nginx will make request to http://localhost:3000/home

If for example we want to proxy only specific urls (let’s say only *.php) we could do this:

location ~ \.php {
proxy_pass http://localhost:3000/
}

Nginx has to be built with sub_filter module.
The example below will override all localhost:3000 to toni-develops.com:80

...

server {
listen       8081;
server_name  toni-develops.com;

location / {
proxy_pass http://localhost:3000/;
proxy_buffers 8 1024k;
proxy_buffer_size 1024k;
sub_filter 'localhost:3000'  'toni-develops.com:80';
sub_filter_once off;
}

...

# Unique-paths

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

How many possible unique paths are there?

Note: m and n will be at most 100.

Example 1:

Input:

 m = 3, n = 2


Output:

 3


Explanation:

From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right


Example 2:

Input:

 m = 7, n = 3


Output:

 28

This problem was taken from Leetcode unique paths and Leetcode_unique_paths_part_II

## Solution

Since we can move only right or down on every cell in the first row we will have only one place from where we can come and this is the cell before. And same for the first vertical row.

Then after we figured out that there is only one way to reach each cell in the first row and the first column (which is from the cell before) we could start calculating possible ways to go to the next cells.
Let’s look at the cell in the second row and second column.There are actually two possible ways to go there: from the cell above, and the cell before, so 2 possible ways. (figure below).
The cell in the third column on the second row: same 1 way from the cell above, and from the cell before. But since there are already 2 ways to reach the cell before the total ways to reach this cell is: 1 + 2 = 3.

The solution:

/**
* @param {number} m
* @param {number} n
* @return {number}
*/
var uniquePaths = function(m, n) {

var memo = [];

for(var i=0;i < n; i ++) {
for(var j = 0; j < m; j ++) {
var index = (i * m) + j;
if(i == 0) {
memo[index] = 1;
}
else if(j == 0) {
memo[index] = 1;
}
else {
var up = index - m;
var left = index - 1;
memo[index] = memo[up] + memo[left];
}
}
}
return memo[memo.length - 1];
}

console.log(uniquePaths(7,3));

## Unique paths with obstacles.

/**
* @param {number[][]} obstacleGrid
* @return {number}
*/
var uniquePathsWithObstacles = function(obstacleGrid) {
var m = obstacleGrid[0].length;
var n = obstacleGrid.length;
var row = 0;
if(obstacleGrid[0][0] == 1)
return 0;

var memo = [];

for(var i=0;i < n; i ++) {
for(var j = 0; j < m; j ++) {
var index = (i * m) + j;
if(i == 0) {
if(obstacleGrid[i][j] == 1 || (j > 0 && memo[index -1] == 0))
memo[index] = 0;
else
memo[index] = 1;
}
else if(j == 0) {
if(obstacleGrid[i][j] == 1 || (i > 0 && memo[index - m] == 0))
memo[index] = 0;
else
memo[index] = 1;
}
else {
var up = index - m;
var left = index - 1;
if(obstacleGrid[i][j] == 1)
memo[index] = 0;
else
memo[index] = memo[up] + memo[left];
}
row += memo[index] ? 0 : 1;
}
if(row == m)
return 0;
row = 0;
}
return memo[memo.length - 1];
};

var grid = [
[0,0,0],
[0,1,0],
[0,0,0]
];

console.log(uniquePathsWithObstacles(grid));

# Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

begin to intersect at node c1.

Example 1:

This problem was taken from Leetcode

## Solution

We are not asked to compare the values inside the linked lists but the list node objects, so we could ignore the values of the list.

#### Approach 1: Brute Force

For each node ai in list A, traverse the entire list B and check if any node in list B coincides with ai.

Complexity Analysis

• Time complexity : O(mn).
• Space complexity : O(1).

#### Approach 2: Calculating the length of the two linked lists and compare the elements that could potentially intersect.

• Time complexity : O(m+n).
• Space complexity : O(m) or O(n).
 function ListNode(val) {
this.val = val;
this.next = null;
}

/**
* function ListNode(val) {
*     this.val = val;
*     this.next = null;
* }
*/

/**
* @return {ListNode}
*/

let countA = 0;
while(node != null ) {
node = node.next;
countA ++;
}

let countB = 0;
while(node != null ) {
node = node.next;
countB ++;
}

let longList, shortList, diff, iteratorLongLength,iteratorShortLength;
if(countA > countB)
else

let i = 0;
while(shortList != null) {
if(i < diff ) {
longList = longList.next;
}
else {
console.log("long list, short list", longList.val, shortList.val);
if(longList == shortList)
return longList.val;
longList = longList.next;
shortList = shortList.next;
}

i ++;
}
};

console.log (getIntersectionNode(headA, headB) );

what we just did:
– we calculated the length of the first list to be 5 and the second 6 (first and the second loop)
– the third loop is doing two things:
– first since the difference between the shorter and the longer list is 1 we move the cursor to the second element of the longer list (lines 59-61)
– after we position the longer list cursor at the second element we could start comparing (line 64)

If we execute the function we will see this result:

long list, short list 0 4 long list, short list 1 1 long list, short list 8 8

And the third element is exactly where the intersection is.

#### Approach 3: Traverse both lists and when reaching the end of each one, move the pointer to the opposite list and traverse again till intersection is found.

• Time complexity : O(m+n).
• Space complexity : O(m) or O(n).

This basically is the same concept as in the example above, just written in a bit more elegant way.

 function ListNode(val) {
this.val = val;
this.next = null;
}

/**
* function ListNode(val) {
*     this.val = val;
*     this.next = null;
* }
*/

/**
* @return {ListNode}
*/

let swapA = false;
let swapB = false;
var i = 0;
while(nodeA != null && nodeB!=null ) {
// node A
if(!swapA && nodeA.next == null) {
swapA = true;
}
else {
nodeA = nodeA.next;
}
// node B
if(!swapB && nodeB.next == null) {
swapB = true;
}
else {
nodeB = nodeB.next;
}

if(nodeA === nodeB)
return nodeA.val;

}
};

console.log (getIntersectionNode(headA, headB) );

what we just did:
– traverse listA and listB till we reach the end of each one (lines 47 and 55) .
– once we reach the end of each list we point the cursor to the opposite list (lines 43 and 51)

#### Approach 4: Hash Table

Traverse list A and store the address / reference to each node in a hash set. Then check every node bi in list B: if bi appears in the hash set, then bi is the intersection node.

Complexity Analysis

• Time complexity : O(m+n).
• Space complexity : O(m) or O(n).
 function ListNode(val) {
this.val = val;
this.next = null;
}

/**
* function ListNode(val) {
*     this.val = val;
*     this.next = null;
* }
*/

/**
* @return {ListNode}
*/

let hashMap = {};
while(node != null ) {

hashMap[node.val] = node;
node = node.next;
}

while(node != null) {
let val = node.val;
if(hashMap[val] == node) {
return val;
}
node = node.next;
}
};

console.log ("result: ", getIntersectionNode(headA, headB) );

# Check if string has all unique characters

Implement an algorithm to determine if a string (of characters from ‘a’ to ‘z’) has all unique characters or not.

Example 1:

var s = "abcde";
returns true;


Example 2:

var s = "abcade";
returns false;


## Solution

Solution 1: The brute force solution will be to iterate through all characters and compare with all other characters.

function areCharactersUnique(s) {
for(let i=0; i < s.length; i++) {
for(let j=0; j < s.length; j++) {
if(i == j)
continue;
if(s[i] == s[j]) {
return false;
}
}

}
return true;
}

console.log(areCharactersUnique(s));

Solution 2: Using an array (or hashMap table) with key equal to the ASCII character code.

function areCharactersUnique(s) {
var checker = new Array(26);
for(let i=0; i < s.length; i++) {
var pos = s[i].charCodeAt(0) - 'a'.charCodeAt(0);
if(typeof checker[pos] != 'undefined') {
return false;
}
checker[pos] = 1;
}
return true;
}

var s = "abcde";

console.log(areCharactersUnique(s));

Let’s make it more challenging and prohibit the use of additional data structures like count array, hash, etc.

Solution 3: Using bitwise operations to store into 32 bit if one of all 26 characters is presented or not.
We have 26 letters (from a to z). Let’s imagine that we could have 26 empty slots that we could set up to true if the character exists, pretty much as if we have a hashTable.
for simplicity I will use only 6 slots (from a to G) instead of all 26 that represent the whole alphabet.
In addition we have to mention that the slots are actually 32 (this is usually the length of an integer in JavaScript but we need only 26)

 6 5 4 3 2 1 0 G F E D C B A false false false false false false false

Given the string: ‘ABCG’ for example we will end up with this matrix.

 6 5 4 3 2 1 0 G F E D C B A true false false false true true true

But this could be stored into 32bit value using bitwise operations. The binary representation of the matrix above will be:  1000111

The solution:

function areCharactersUnique(s) {
var checker = 0;

for(let i=0; i < s.length; i++) {
// Charcode of a is 97 but we want to start with 0
var val = s[i].charCodeAt(0) - 'a'.charCodeAt(0);
// & - Sets each bit to 1 if both bits are 1
// examples:
// 1 & 10 = 0
// 1 & 101 = 1
if(checker & ( 1 << val)) {
return false;
}

// | - Sets each bit to 1 if one of two bits is 1
// examples:
// 1 | 10 = 11
// 1 | 1 = 1
checker = checker | ( 1 << val);
}
return true;
}

what we just did:
– we started with creating a loop to go through all characters
– we set up an empty value checker to store if the character is used or not (this is the binary representation of the matrix above)
– (line 6) grabbing the value for each letter in the string but removing ‘a’ = 97 so ‘a’ character will be equal to 0 and z = 26
– (line 19) we are setting the position of the character into the checker to true using bitwise shift left (1 << a) and preserving other already set positions using bitwise | ‘or’
– (line 11) using the same technique but with bitwise & ‘and’ we check if the character position is set to true or not.

Here is a step by  step example for ‘ABCG’ character:
– initially checker = 0 // or the binary representation is '00000000...0'
– we are going to insert a using Zero fill left shift. This is basically going to add ‘1’ followed by as many ‘0’ to the right of the checker as the value of ‘a’ is. In this case 0, so schecker = 1 // binary '00000000...1

– next step inserting ‘b’ follows the same procedure: b = 1, (1 << b) = 2 '000000...10' but we also want to preserve whatever was already inserted so we use bitwise ‘|’ ‘or’ which sets each bit to 1 if one of two bits is 1.
so
checker = checker | (1 << b) = 2
or the binary representation will be:
checker = '00000000...1' | (1 << b) = '000000000...11'

and the same for the rest of the characters

var a = 0;
var b = 1;
var c = 2;
var d = 3;
var e = 4;
var f = 5;
var g = 6;

var s = "abcg";
var checker = 0;

checker = checker | (1 << a);   // 1
checker = checker | (1 << b);   // 11
checker = checker | (1 << c);   // 111
checker = checker | (1 << g);   // 1000111



Let’s modify the problem, and ask to return the index of the first unique character in the string.
For example for string ‘abcac’ the return will be the index of b – ‘1’
This problem is asked in Leetcode

/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function(s) {

let lastSingle = null;
let hashMap = {};
for(var i = 0;i < s.length; i ++) {
var val = s[i];
hashMap[val] =  hashMap[val] == undefined ? i: 'not-unique';
}

for(let i=0; i < s.length; i++) {
var key = s[i];
if(hashMap[key] != 'not-unique') {
return hashMap[key];
}
}
return -1;

}
{"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 1, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}