20 decembrie 2023

50 DSA-Questions: Arrays #1, #2

#1. Two Sum
Given an array of integer nums and an integer target, return indices of the two numbers such that they add up to the target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i=0; i<nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], new ArrayList<>()); // handle duplicate elements
            }
            map.get(nums[i]).add(i);
        }

        int [] indices = new int[2];
       
        for (int i=0; i<nums.length; i++) {
            int element = nums[i];
            map.get(element).remove(0);
            int key = target - element;
            if (map.containsKey(key) && !map.get(key).isEmpty()) {
                indices[0] = i;
                indices[1] = map.get(key).get(0);
                return indices; // assume exactly one solution
            }
        }

        return indices;
    }
}

#2. Best Time to Buy and Sell Stock
You are given an array of prices where prices[i] is the price of a given stock on an i-th day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
class Solution {
    public int maxProfit(int[] prices) {
        int[] min = new int[prices.length];
        min[0] = prices[0];
        for (int i = 1; i < prices.length; i++) {
            min[i] = prices[i] < min[i-1] ? prices[i] : min[i-1]; // min pana la momentul i, crescator
        }

        int[] max = new int[prices.length];
        max[prices.length - 1] = prices[prices.length - 1];
        for (int i = prices.length - 2; i > 0; i--) {
            max[i] = prices[i] > max[i+1] ? prices[i] : max[i+1]; // max pana la momentul i, descrescator
        }

        int maxProfit = 0;
        for (int i = 1; i < prices.length; i++) {
            int profit = max[i] - min[i];
            if (profit > maxProfit) {
                maxProfit = profit;
            }
        }

        return maxProfit;
    }
}

13 decembrie 2023

Unix/networking interview questions

Lista proceselor in executie:

> px aux

> ps -l

> ps -e


Get thread dump of running Java processes:

> jps -lv      # afla [pid] proces java

> kill -3 [pid]


GREP - cauta linii in fisier text folosind un regex

> cat file.txt | grep "Cauta un rand"


TAIL - tipareste ultimele linii dintr-un fisier (default ultimele 10)

> cat file.txt | tail -n 2


LESS - afiseaza cate o pagina (nu incarca tot)

> less file.txt

> cat file.txt | less -p "pattern"   # afiseaza de la acel rand incolo


MORE - la fel ca LESS, insa navigarea inapoi e limitata si nu are optiuni de cautare 


Diferenta TCP si UDP

TCP = transmission control protocol, bazat pe conexiune, de incredere dar mai lent, verificare buna de erori. Potrivit pt transmitere de texte, fisiere, navigare pe internet.

UDP = user datagram protocol, fara conexiune, rapid dar pierde date (nu retransmite), verificare minimala de erori, permite broadcasting. Potrivit pt transmitere continut media (video, audio), jocuri in retea.

In caz de coliziune, ruterele prefera pachetele TCP si renunta la cele UDP.


Aflare spatiu liber pe disc:

> df


Aflare marime folder

> du

27 iunie 2023

Xor Linked List

O listă simplu-înlănțuită cu proprietăți de dublu-înlănțuită, care are nevoie de un singur pointer în loc de doi. 

Sună frumos în teorie, dar este inaplicabil în Java. De fapt, este o aplicație pur teoretică întrucât memoria nu mai este o problemă acum, fiind foarte ieftină. De asemenea, nu te scutește de parcurgerea întregii liste, la fel ca listele simplu-înlănțuite. Pe scurt, brain fuck for no reason, mai jos este o tentativă de implementare (netestată, pentru că... Java):

Notă: getPrev și getNext au nevoie de nodul următor respectiv anterior pentru a-și îndeplini funcția, ceea ce presupune că ai parcurs lista înainte. Doar oleacă mai flexibil, merită oare? Sau îmi scapă ceva?


public class MemEffLinkdListTest {
Node head;

/* Xor Linked List */

private void initList(int length) {
if (length < 1) {
throw new MyBusinessException("Invalid length!");
}

head = new Node("A0");
Node prev = null;
Node current = head;

for (int i = 1; i < length; i++) {
Node next = new Node("A" + i);
Node ptr = prev ^ next; // not possible in Java, we don't have access to memory addresses
current.setPtr(ptr);

prev = current;
current = next;
}
}

private Node getNext(Node current, Node prev) {
return current ^ prev; // not possible in Java
}

private Node getPrev(Node current, Node next) {
return current ^ next; // not possible in Java
}

private class Node {
private String data;
private Node ptr;

public Node(String data) {
this.data = data;
this.ptr = null;
}

public void setPtr(Node ptr) {
this.ptr = ptr;
}

public Node getPtr() {
return ptr;
}

public String getData() {
return data;
}
}
}

24 mai 2023

Angular: trimitere parametri pe route

 Fisierul de routing.ts contine calea de baza extinsa cu 2 parametri (policeReportId si source): 

{
path: Path.POLICE_REPORT_DETAILS + '/:policeReportId',
component: PoliceReportDetailsPage,
canActivate: [Guard]
},
{
path: Path.POLICE_REPORT_DETAILS + '/:policeReportId/:source',
component: PoliceReportDetailsPage,
canActivate: [Guard]
},

In componenta corespunzatoare caii se cauta de parametri:

constructor(private route: ActivatedRoute) {
}
ngOnInit(): void {
if (isNotNullOrUndefined(this.route.snapshot.paramMap?.get('source'))) {
switch (this.route.snapshot.paramMap.get('source')) {
case RedirectSource.DECISIONS:
// do something
}
}
}


In componenta care face redirectarea se specifica parametrul suplimentar:

refreshPage(path: string): void {
path = path + '/' + RedirectSource.DECISIONS;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() =>
this.router.navigate([path]));
}

P.S. a nu se uita:
<router-outlet></router-outlet>

03 aprilie 2023

Angular form validations triggered at field change

this.form.controls[this.FIELDS.field1].markAsTouched(); // if not touched, it won't validate although it has a value

this.form.controls[this.FIELDS.field].valueChanges.subscribe(() => {

            this.form.controls[this.field1].updateValueAndValidity();

            this.form.controls[this.field2].updateValueAndValidity();

});