What I learned?
I learned the following topics:
use of Static keyword in javascript
bind keyword in javascript
What I developed/solved?
Solved one leetcode problem called Two sum
Code snippet/Screenshots/notes
Leetcode problem 1. Two sum
Problem statement: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Example.
Output: [0,1]
Output: [1,2]
Brute force approach
public:
vector<int> twoSum(vector<int>& nums, int target) {
int size = nums.size();
vector<int> ans;
for (int i = 0; i < size; i++) {
int flag = 0;
for (int j = i+1; j < size; j++) {
/* when the summation of these two becomes equal or up to target
return the indexes of both
*/
int sum = nums[j] + nums[i];
if (sum == target && i != j){
ans.push_back(i);
ans.push_back(j);
/* flag used to determine that we have found
that element whose summmation is equal to target
*/
flag = 1;
}
}
//flag = 1 meaning we got our answer so no need to go further
if(flag == 1){
break;
}
}
return ans;
}
};
// Time complexity: O(n)*O(n)=O(n^2)
// Space comlexity: O(1) as we aren’t using extra space
optimal approach using hashmap
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> m;
vector<int> v;
for (int i = 0; i < nums.size(); i++) {
int first = nums[i];
int second = target – first;
if (m.find(second) != m.end()) {
v.push_back(m[second]);
v.push_back(i);
}
m[first] = i;
}
return v;
}
};
/* Time complexity: O(N * logN), where n = number of elements in an array
logN = time takes for insertion in map
Space complexity: O(N)
*/
Static keyword in JavaScript
static keyword is used to define a static method for a class.
static methods aren’t called on instances of the class. Instead, they’re called on the class itself.
You call it on the class, but on the instances of class
Bind keyword
bind() method in JavaScript is a method that allows you to set the this value in a function.
<head>
<meta charset=“UTF-8”>
<meta name=“viewport” content=“width=device-width, initial-scale=1.0”>
<title>Bind</title>
</head>
<body>
<button>Click me</button>
</body>
<script>
class React {
constructor() {
this.library = “React“
this.server = “https://localhost:3000“
document.querySelector(‘button‘)
.addEventListener(‘click‘, this.handleClick.bind(this)) //this for current context
}
handleClick() {
console.log(“button clicked successfully!“)
console.log(this.server)
}
}
const my_app = new React();
</script>
</html>