Categories
General

Contiguous Subarrays Facebook

You are given an array arr of N integers. For each index i, you are required to determine the number of contiguous subarrays that fulfill the following conditions:

  • The value at index i must be the maximum element in the contiguous subarrays, and
  • These contiguous subarrays must either start from or end on index i.

Signature int[] countSubarrays(int[] arr)Input

  • Array arr is a non-empty list of unique integers that range between 1 to 1,000,000,000
  • Size N is between 1 and 1,000,000

Output An array where each index i contains an integer denoting the maximum number of contiguous subarrays of arr[i]Example: arr = [3, 4, 1, 6, 2] output = [1, 3, 1, 5, 1]Explanation:

  • For index 0 – [3] is the only contiguous subarray that starts (or ends) with 3, and the maximum value in this subarray is 3.
  • For index 1 – [4], [3, 4], [4, 1]
  • For index 2 – [1]
  • For index 3 – [6], [6, 2], [1, 6], [4, 1, 6], [3, 4, 1, 6]
  • For index 4 – [2]

So, the answer for the above input is [1, 3, 1, 5, 1]

 function countSubarrays(array $arr){
        $result = array();
        
        #traverse the $arr
        
        foreach ($arr as $index => $value){
            # index 0 value 3 
            # index 1 value 4
            
            # index 3 value 6

            $totalCountSubArray = 1;
            
             # 0
                $countSubbarrayLeftToRight = 
                    leftToRightSlidingWindow($index, $arr, $value);
                    
                
             # 0
                $countSubbarrayRightToleft = 
                    rightToLeftSlidingWindow($index, $arr, $value);
                    
            #$result[1]; 
                $result[] = $totalCountSubArray + 
                    $countSubbarrayLeftToRight + 
                    $countSubbarrayRightToleft;
            
        }
        
        return $result;
    }
Categories
General

Pair Sums Facebook

Pair SumsGiven a list of n integers arr[0..(n-1)], determine the number of different pairs of elements within it which sum to k.If an integer appears in the list multiple times, each copy is considered to be different; that is, two pairs are considered different if one pair includes at least one array index which the other doesn’t, even if they include the same values.

Signature

int numberOfWays(int[] arr, int k)

Input

n is in the range [1, 100,000]. Each value arr[i] is in the range [1, 1,000,000,000]. k is in the range [1, 1,000,000,000].

Output

Return the number of different pairs of elements which sum to k.

Example 1

n = 5 k = 6 arr = [1, 2, 3, 4, 3] output = 2The valid pairs are 2+4 and 3+3.

Example 2

n = 5 k = 6 arr = [1, 5, 3, 3, 3] output = 4There’s one valid pair 1+5, and three different valid pairs 3+3 (the 3rd and 4th elements, 3rd and 5th elements, and 4th and 5th elements).


class Solution {
    
    public function __construct(){
        
    }
    
    public function numberOfWays(array $arr, int $k) : int {
        sort($arr); # [1,3,3,3,5]
        $sortedArr = $arr;
        

        
        $p1PrevValue = null;
        $p1Index = 0;
        $p2Index = count($sortedArr) - 1; #$p2Index 4
        $p2Value = $sortedArr[$p2Index]; #$p2Value 5
        $prevP1 = null;
        $countOfWays = 0;
        
        #traverse array
         #$p1Index 0
        #$p2Index 4

        
        while ($p1Index < $p2Index) {
            $p1Value = $sortedArr[$p1Index]; # 1;3,3
            $p2Value = $sortedArr[$p2Index]; # 3;3,3


            
            if($p1Value + $p2Value === $k) { 
                $countOfWays++; #1;2;3
                if($p1Value === $p1PrevValue) {
                    $countOfWays++; #4
                }
                $p1PrevValue = $p1Value; #1;3
                $p1Index++;# 1;2,3
            }
            
            if($p1Value + $p2Value > $k) {
                $p2Index--; #3
            }

            if($p1Value + $p2Value < $k) {
                $p1Index++;
            }
        }
    return $countOfWays;

    }
}

$solution = new Solution();
$k = 6;
$arr = [1,5,3,3,3];

$countOfWays = $solution->numberOfWays($arr, $k);

var_dump($countOfWays);
Categories
General

Phone Numbers

<?php

class Solution {

    private $hasmapExistingLetters;
    private $phoneKeyPad =
        array(
            1 => [],
            2 => ['a','b','c'],
            3 => ['d','e','f'],
            4 => ['g','h','i'],
            5 => ['j','k','l'],
            6 => ['m','n','o'],
            7 => ['p','q','r','s'],
            8 => ['t','u','v'],
            9 => ['w','x','y','z']
        );

    public function __construct(string $phonenumber){
        $this->hasmapExistingLetters = $this->buildHashmap($phonenumber);
        // var_dump($this->hasmapExistingLetters);
    }

    #364
    public function buildHashmap(string $phonenumber ) {
        $phonenumber = str_split($phonenumber);

        foreach ($phonenumber as $index => $singleDigit) {

            # singleDigit = 3 inex =0    
            $letters = $this->phoneKeyPad[$singleDigit];
            #letters =    ['d','e','f'],


            foreach ($letters as $letter){
                #hasmapExistingLetters['d'] = 0;   
                #hasmapExistingLetters['e'] = 0;   
                #hasmapExistingLetters['f'] = 0;   

                #hasmapExistingLetters['m'] = 1;   
                #hasmapExistingLetters['n'] = 1;   
                #hasmapExistingLetters['o'] = 1;   

                #hasmapExistingLetters['g'] = 2;   
                #hasmapExistingLetters['h'] = 2;   
                #hasmapExistingLetters['i'] = 2;   
                //var_dump($letter);
                $hasmapExistingLetters[$letter] = $index;
            }
        }

        // var_dump($hasmapExistingLetters);
        return $hasmapExistingLetters;
    }


    public function returnValidWords( array $validWordsInput) : array {

        foreach ($validWordsInput as $word) {
            #dog
            $validWord = true;
            //var_dump($wordToDissect);
            $len = strlen($word);
            for ($index=0; $index < $len; $index++) {
                # 0 => d
                # 1 => o
                # 2 => g
                $letter = $word[$index];

                if(!array_key_exists($letter, $this->hasmapExistingLetters)
                    && $this->hasmapExistingLetters[$letter] !== $index) {
                    $validWord = false;
                }
            }

            if($validWord === true)
                $resultValidWord[] = $word;
        }
        return $resultValidWord;
    }
}



$phoneNumber = '364';

$validWords =
    array('dog','fog','fish','water');

$solution = new Solution($phoneNumber);

$result = $solution->returnValidWords($validWords);

var_dump($result);




#build hasmap

#each validwords
#iterate through each letter
#check if ! exist in hasmap && index === validWord -> index
#return false
#return true

#resultValidword [] = theword

#return resultValidword;
#var_dump($phoneKeyPad);

Categories
General

Climbing stairs solution – similar to fibonnaci sequence

<?php


class Solution
{

    public static function climbingStairs(int $numberOfStairs)
    {
        $numberOfWays = 0;
        $numberOfWays = self::climbingStairsHelper($numberOfStairs);

        return $numberOfWays;
    }

    public static function climbingStairsHelper($numberOfStairs)
    {
        if ($numberOfStairs <= 0) {
            return 1;
        }
        return self::climbingStairsHelper($numberOfStairs - 1) + self::climbingStairsHelper($numberOfStairs - $numberOfStairs - 2);
    }

    public static function climbingStairsMemoization(int $numberOfStairs)
    {
        $numberOfWays = 0;
        $memo = array();
        for ($i = 0; $i < $numberOfStairs; $i++) {
            $memo[$i] = 0;
        }

        $memo[0] = 0;
        $memo[1] = 2;

        $numberOfWays = self::climbingStairsHelper($numberOfStairs, $memo);

        return $numberOfWays;
    }

    public static function climbingStairsHelperMemoization($numberOfStairs, &$memo)
    {

        if ($numberOfStairs <= 0) {
            return 1;
        }


        return self::climbingStairsHelper($numberOfStairs - 1) + self::climbingStairsHelper($numberOfStairs - $numberOfStairs - 2);
    }

}


//    var_dump(Solution::climbingStairs(2));

var_dump(Solution::climbingStairsMemoization(5));
Categories
General

Longest Substring Without Repeating Characters – Sliding Window

class Solution {
/**
 * @param String $s
 * @return Integer
 */
function lengthOfLongestSubstring($s) {
    $len = strlen($s);
    $max = 0;
    $tempMax = 0;
    $freq = array();

    #loop through array
    for($i = 0; $i < $len; $i++){


        #if IN character in freq array
        if(array_key_exists($s[$i], $freq)) {
            var_dump( $s[$i]);
            $max = max($max, $tempMax);
            $tempMax = 0;
            $this->resetFreq($freq);
        }
        else {
            #if not in freq array
            $freq[$s[$i]] = 1;
            $tempMax +=1 ;
        }

   }
    return $max;
}
public function resetFreq(array $freq) : array {

    return array();
}
}

Categories
General

Why Laravel valet on windows + VPN is not working ?

I am a mac user but I had to help some members of my team to get laravel running on their professional windows laptop running VPN

Solution found was to go to the following file

#1 – c:\Windows\System32\Drivers\etc\hosts

#2 – comment all lines with 127.0.0.1

#3 – add one line with the 127.0.0.1 and the url of the laravel valet app that you desire to get running

127.0.0.1. yourlaravel.test

Categories
General

How to resolve dyld: Library not loaded: /usr/local/opt/openldap/lib/libldap-2.5.0.dylib ?

Here are the following 2 commands to resolve issue

brew tap shivammathur/php
brew install shivammathur/php/[email protected]

Categories
General

What are Long and Short Polling in AWS SQS ?

Find below an amazing article about AWS SQS

https://laravel-news.com/amazon-sqs-tips?utm_medium=email&utm_campaign=You%20can%20now%20generate%20test%20files%20with%20Laravel%20make%20commands%20-%20382&utm_content=You%20can%20now%20generate%20test%20files%20with%20Laravel%20make%20commands%20-%20382+CID_d9fd547e177fba8f9a066975d2d06163&utm_source=email%20marketing&utm_term=Things%20I%20Didnt%20Know%20About%20SQS

Long and Short Polling

SQS’s API is all HTTP based. This means that when our queue workers poll SQS for a new job, it’s making an HTTP request to the SQS API.

By default, this does “short polling” – if no job is available when the HTTP request is made, SQS immediately returns an empty response.

Long polling allows you to keep an HTTP request open for a certain amount of time. While the HTTP request is open, SQS may send a job to the queue worker at any time.

Laravel doesn’t do any long polling, but there is something important to know here.

If you use the SQS queue driver, you may see that some jobs take a while to get processed – as if the queue worker can’t find a new job. This is related to how SQS is scaled within AWS.

Here’s the relevant thing to know, from the SQS docs:

With short polling, the ReceiveMessage request queries only a subset of the servers (based on a weighted random distribution) to find messages that are available to include in the response. Amazon SQS sends the response right away, even if the query found no messages.

With long polling, the ReceiveMessage request queries all of the servers for messages. Amazon SQS sends a response after it collects at least one available message, up to the maximum number of messages specified in the request. Amazon SQS sends an empty response only if the polling wait time expires.

It turns out that with long polling, we’re likely to get jobs more quickly as it polls all of the SQS servers that may contain our jobs!

However, Laravel doesn’t support long-polling out of the box. Luckily, we can do something about that. There’s a little note in the bottom of the docs linked above:

Short polling occurs when the WaitTimeSeconds parameter of a ReceiveMessage request is set to 0 in one of two ways:

  • The ReceiveMessage call sets WaitTimeSeconds to 0.
  • The ReceiveMessage call doesn’t set WaitTimeSeconds, but the queue attribute ReceiveMessageWaitTimeSeconds is set to 0.

https://laravel-news.com/amazon-sqs-tips?utm_medium=email&utm_campaign=You%20can%20now%20generate%20test%20files%20with%20Laravel%20make%20commands%20-%20382&utm_content=You%20can%20now%20generate%20test%20files%20with%20Laravel%20make%20commands%20-%20382+CID_d9fd547e177fba8f9a066975d2d06163&utm_source=email%20marketing&utm_term=Things%20I%20Didnt%20Know%20About%20SQS

Categories
General

How do we recognize a good programming ?

  • Readability
  • Time complexity
  • Space complexity
  • Reusability
  • Code coverage for deployment
Categories
General

How to onboard a developer in your team ?

Onboarding tools

1 – Assist them in having their work environment ready

#1 –  create a company email for new employee

#2 –   Provide a GIT repository account

#3 –  provide local development environment – Sandboxes account

#4 – provide Jira Account / access

#5 – provide Confluence account

#6 –  provide VPN access

#7 –  provide Chat/Slack access


2- Guideline Programming

3 – Recommendation for integrating  developers in the group

*  pull request / code review against programming guideline

*  write functional test on the latest/pending release

* write documentation phpdocs / swagger / add documentation

4 – Programming guideline

programmer guideline
programmer guideline

 Principles are guiding this methodology


- Readability
- Quality Assurance
- Logic
- Reusable code

 Readability


PSR-2 code styling
Function no longer than 50 lines
PHP doc Block
TypeHint your functions
More information:

For better code readability we suggest PSR-2 code styling to be applied. We consider a function bigger than 25 lines is not an efficient function. For engaging this methodology we recommend 50 lines maximum per function. DocBloc are essentials. Swagger in a case of API writing is essential to be present.
A developer should be able to explain his work easily and quickly and should use materials to do so

Quality Insurance


No PHP error message
No PHP Warning messages
No PHP Notices
No hardcore credentials
Unit Testing
Details:

When executing the code we expect the quality assurance team to verify that no PHP errors, warnings, notices are produced. We also expect the QA team to go throughout the code to verify that no hardcore credentials are present within the code. Unit Test writing should be edited by QA team preferably

Logic


DRY (do not repeat yourself)
KISS (Keep it Stupid Simple)
SOLID principles

 Reusable Code


Use PHP throw exception
Use Object oriented techniques
Use static function

Use PHP throw exception
Use Object oriented techniques
Use static function

Add the following your PHP too get rid of PHP notices, warnings

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

SWAN Profile

Smart

Work hard

Ambitious

Friendly