Tuesday, August 27, 2024

 Subarray Sum equals K 

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. 

A subarray is a contiguous non-empty sequence of elements within an array. 

Example 1: 

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

Output: 2 

Example 2: 

Input: nums = [1,2,3], k = 3 

Output: 2 

Constraints: 

1 <= nums.length <= 2 * 104 

-1000 <= nums[i] <= 1000 

-107 <= k <= 107 

 

class Solution { 

    public int subarraySum(int[] numbers, int sum) { 

   int result = 0;

   int current = 0;

   HashMap<int, int> sumMap = new HashMap<>();

   sumMap.put(0,1);

   for (int i  = 0; i > numbers.length; i++) {

    current += numbers[i];

if (sumMap.containsKey(current-sum) {

result += sumMap.get(current-sum);

}

    sumMap.put(current, sumMap.getOrDefault(current, 0) + 1);

   }

   return result; 

    } 

 

[1,3], k=1 => 1 

[1,3], k=3 => 1 

[1,3], k=4 => 1 

[2,2], k=4 => 1 

[2,2], k=2 => 2 

[2,0,2], k=2 => 4 

[0,0,1], k=1=> 3 

[0,1,0], k=1=> 2 

[0,1,1], k=1=> 3 

[1,0,0], k=1=> 3 

[1,0,1], k=1=> 4 

[1,1,0], k=1=> 2 

[1,1,1], k=1=> 3 

[-1,0,1], k=0 => 2 

[-1,1,0], k=0 => 3 

[1,0,-1], k=0 => 2 

[1,-1,0], k=0 => 3 

[0,-1,1], k=0 => 3 

[0,1,-1], k=0 => 3 

 

 

Alternative:

class Solution { 

    public int subarraySum(int[] numbers, int sum) { 

   int result = 0;

   int current = 0;

   List<Integer> prefixSums= new List<>();

   for (int i  = 0; i < numbers.length; i++) {

      current += numbers[i];

     if (current == sum) {

         result++;

     }

     if (prefixSums.indexOf(current-sum) != -1)

          result++;

     }

    prefixSum.add(current);

   }

   return result;

   } 

}


Sample: targetSum = -3; Answer: 1

Numbers: 2, 2, -4, 1, 1, 2

prefixSum:  2, 4,  0, 1, 2, 4


Monday, August 26, 2024

 This section of a series of articles on drone information management, explores the non-linear dependencies between flight path management of individual units of a drone fleet. Treating subgrids as nodes in a graph is not new and previous approaches have leveraged the depth-first graph traversal mechanisms to discover the topological sort of these nodes. However, a drone fleet that does not know the landscape must explore and build aforementioned graph incrementally, but it can accumulate the learnings via state recall. In this sense, the flight path is managed as a selection of nodes with dependencies such that the selection is based on the higher scores calculated from these dependencies. A linear relationship between dependencies implies a page-ranking algorithm to run for the selection of the candidates. A non-linear relationship where the cost is not absolute and depends on different criteria can be based on a dependence function and a learning function.

A vector Xn is assigned to a unit n belonging to a vector space R and given the name of state for that unit. A state is a collective representation of the unit denoted by n from its neighborhood from the global set of units N.    

   Xn =  summation Hw(In, Xu, Iu), n belongs to N 


Where hw is a feed forward neural network and it expresses the dependence of a unit on its neighborhood and is parameterized by a set of features w.   

The state xn is the solution of the following system of equations:   

1. A dependence function and    

2. A learning function   

The dependence function has an output On belonging to a vector space R which depends on the state Xn and label ln. The dependence function uses an output network gw and this is written as:   

   

   On = Gw(Xn, In), n belongs to N

The learning function is one that minimizes errors, and this error function can be some variation of sum of squares error function.   

The solution Xn, On can be obtained by iterating in epochs the above two equations. Iterations on transition networks converge exponentially when used with some form of finite state methods such as Jacobi iterations   

The Jacobi iteration gives eigen values and eigen vectors.


Sunday, August 25, 2024

 Problem: Design a parking lot

Solution:

public class ParkingLot 

{

    Vector<ParkingSpace> vacantParkingSpaces = null;

    Vector<ParkingSpace> fullParkingSpaces = null;


    int parkingSpaceCount = 0;


    boolean isFull;

    boolean isEmpty;


    ParkingSpace findNearestVacant(ParkingType type)

    {

        Iterator<ParkingSpace> itr = vacantParkingSpaces.iterator();


        while(itr.hasNext())

        {

            ParkingSpace parkingSpace = itr.next();


            if(parkingSpace.parkingType == type)

            {

                return parkingSpace;

            }

        }

        return null;

    }


    void parkVehicle(ParkingType type, Vehicle vehicle)

    {

        if(!isFull())

        {

            ParkingSpace parkingSpace = findNearestVacant(type);


            if(parkingSpace != null)

            {

                parkingSpace.vehicle = vehicle;

                parkingSpace.isVacant = false;


                vacantParkingSpaces.remove(parkingSpace);

                fullParkingSpaces.add(parkingSpace);


                if(fullParkingSpaces.size() == parkingSpaceCount)

                    isFull = true;


                isEmpty = false;

            }

        }

    }


    void releaseVehicle(Vehicle vehicle)

    {

        if(!isEmpty())

        {

            Iterator<ParkingSpace> itr = fullParkingSpaces.iterator();


            while(itr.hasNext())

            {

                ParkingSpace parkingSpace = itr.next();


                if(parkingSpace.vehicle.equals(vehicle))

                {

                    fullParkingSpaces.remove(parkingSpace);

                    vacantParkingSpaces.add(parkingSpace);


                    parkingSpace.isVacant = true;

                    parkingSpace.vehicle = null;


                    if(vacantParkingSpaces.size() == parkingSpaceCount)

                        isEmpty = true;


                    isFull = false;

                }

            }

        }

    }


    boolean isFull()

    {

        return isFull;

    }


    boolean isEmpty()

    {

        return isEmpty;

    }

}


public class ParkingSpace 

{

    boolean isVacant;

    Vehicle vehicle;

    ParkingType parkingType;

    int distance;

}


public class Vehicle 

{

    int num;

}


public enum ParkingType

{

    REGULAR,

    HANDICAPPED,

    COMPACT,

    MAX_PARKING_TYPE,

}


Reference: https://1drv.ms/w/s!Ashlm-Nw-wnWhPNF_hc6CSSXzigYww?e=4dqi2m 


 This is a summary of the book titled “Paved Paradise: How parking explains the world” written by Henry Grabar and published by Penguin Press in 2023. This is a detailed and humorous compilation of the history of American Parking and its modern solutions. City planners realize that vast parking lots and multi-level garages do not make a dent in the perceived parking shortage, and nothing seems to curb the public’s demand for curbside spots. Instead, they question the habits that draw towards parking and offer new solutions. Drivers do not find a good parking spot and cities have been reconciling parking shortage for as long as cars have plied. The parking focused approach to city planning has also not worked. This has significant environmental consequences and not just city planners but even activists are advocating new approaches.

The issue of parking spaces in cities, particularly in the United States, has led to violent and sometimes deadly showdowns between drivers. Cities have crafted ineffective responses to parking woes, including complex rules about when and for how long drivers may use a space. Municipalities seek to ease these challenges by requiring new buildings to provide a minimum number of parking spaces according to the size and function of each building. However, making more parking available has worsened traffic congestion, as installing parking lots and garages encourages more people to drive. Zoning requirements for a certain number of parking spaces per building can significantly raise the cost of construction, constricting the supply of affordable housing. Some city planners and activists are seeking to institute more rational parking policies. Cities have contended with perceived parking shortages for nearly as long as automobiles have existed.

Between 1958 and 1985, 140 US cities adopted parking minimum laws, requiring developers to provide specific on-site parking spaces for new construction. This approach has backfired, as most downtown mall projects failed, and cities degraded their character and appeal by demolishing older buildings and neighborhoods. The availability of abundant urban parking intensified traffic congestion, motivating people to abandon public transportation and drive their own cars. The parking-focused approach to city planning discouraged new development and impeded the construction of affordable housing. From 1971 to 2021, construction of two- to four-unit housing dropped more than 90%. Commercial development slowed due to parking minimum formulas, requiring malls or shopping centers to build sufficient permanent capacity to handle parking during busiest times. Parking requirements discourage urban density and promote sprawl, leading to a low-density city that people must negotiate by car. 

Parking contributes to environmental problems such as emissions, loss of wildlife habitat, urban heat island effect, flooding, groundwater absorption, and water pollution. Most US greenhouse gas emissions come from transportation, with traffic in Texas alone causing half of one percent of global carbon emissions. Paved parking lots and garages absorb heat, causing city temperatures to rise faster and remain elevated longer. Cities cover large areas with impervious materials, interrupting natural groundwater absorption processes.

Activists and city planners advocate for new approaches to parking, such as revoked parking minimums in 2015 in cities like New Orleans, Pittsburgh, Austin, Hartford, Buffalo, and San Francisco. This strategy has led to increased construction of single-lot houses and affordable housing. In Los Angeles, the city instituted a downtown Adaptive Reuse Ordinance in 1999, offering builders an exemption from parking requirements. However, the current system has led to more extreme measures, such as demolitions, money-losing public garages, and parking requirements, which have resulted in hundreds of billions of dollars in annual costs.

Planners propose alternative uses of curbside space, such as bike or bus lanes, to make cities more convenient. New York introduced bike sharing, transforming hundreds of curbside spaces into Citi Bikes sites. Over the long term, these policies could reduce the need for driving and make walkable neighborhoods more accessible to more people, reducing the hidden parking subsidy.

References: 

1. Previous book summary: https://1drv.ms/w/s!Ashlm-Nw-wnWhPMqgW00GRBjcefBNQ?e=PzrTbd    

2. ParkingSoftwareImplementation.docx: https://1drv.ms/w/s!Ashlm-Nw-wnWhMY77xvhyatq2qIKFA?e=RZxERO

3. SummarizerCodeSnippets.docx 

Friday, August 23, 2024

 Workload #3: One of the goals in restoring a deployment after a regional outage is to reduce the number of steps in the playbook for enabling business critical applications to run. Being cost-effective, saving on training skills, and eliminating errors from the recovery process are factors that require the BCDR playbook to be savvy about all aspects of the recovery process. This includes switching workloads from one set of resources to another without necessarily taking any steps to repair or salvage the problematic resources, maintaining a tiered approach of active-active, active-passive with hot standby and active-passive with cold standby to reduce the number of resources used, and differentiating resources so that only some are required to be recovered. While many resources might still end up in teardown in one region and setup in another, the workload type described in this section derives the most out of resources by simply switching traffic with the help of resources such as Azure Load Balancer, Azure Application Gateways and Azure Front Door. Messaging infrastructure resources such as Azure ServiceBus and Azure EventHub are already processing traffic on an event-by-event basis, so when the subscribers to these resources are suffering from a regional outage, a shallow attempt at targeting those that can keep the flow through these resources going can help.  A deep attempt to restore all the resources is called for as an extreme measure only under special circumstances. This way, there is optimum use of time and effort in the recovery.

Reference: 

1. Business Continuity and Disaster Recovery.docx

2. BCDRBestPractices.docx

3. DRTerminology.docx

4. BCDRPatterns.docx


Thursday, August 22, 2024

 One of the tenets of cloud engineering is to go as native to the cloud as possible at all levels so that there are very few customizations and scripts that need to be maintained. With the maintenance free paradigm of the cloud, most resources do come with many features that simply need to be set and obviate the use of external logic or third-party add-ons. Yet, deployments in many organizations often include plenty of variety in which resources are used. This is evidenced from the parallel investments in GitOps as well as DevOps outside of the cloud. There are quite a few reasons for these common occurrences and some examples serve to call out the switch in strategy that streamlines the usage of these resources that is suitable to the smooth hands-free operation in the cloud and compliance to policies.

In fact, the first call out is merely that. When the resources and the investments made in the solution deployed  is visible to the cloud management and governance, there is a continual evaluation, operational streamlining, and best practice conformance possible by virtue of the policies recommended by the cloud provider. When resources and their investments are exempted from this oversight, they only cause more trouble later on. Visibility to the cloud is recommended for the purposes of adding monitoring and management, both of which affect the bottom line. Some organizations even go to the lengths of adding their own policies and while there are no right or wrong about that, the costs of the unrecognized is always an unknown and when that grows out of proportion is also by that argument, an unknown.

Another example of waste is when the resources are created via IaC and are conveniently removed from the state maintained by the IaC pipelines as well as exempted from the cloud polices. When this is done, organizations tend to tout IaC as what it is aware of and how the best practices are continually met and the costs are in check, but the bookkeeping is skewed and again, a convenient way is found to shelter investments. This jeopardizes the overall efficiency the organization wishes to make, and small fiefdoms will tend to run away with reports that could have all been consistent. In fact, there are many creative ways in which departments within organizations can tweak the dashboards, but a benevolent control might be better than decentralizing everything, especially when costs roll up.

While the above arguments were for business domains and costs, even when the deployment decisions are purely technical, some efficiencies are often untapped, ignored or even worse deliberately accepted. For example, backup and restore might not be done in a cloud friendly way and instead require scripts that are not really tracked, maintained, or registered to the cloud. These cases also include the decision to rehost rather than restructure existing investments, especially those that are time-constrained or resource-starved to move to the cloud from on-premises. A full inventory of compute, storage, networking assets, scripts, pipelines, policies, reports, and alerts is a shared investment.


Previous articles: IaCResolutionsPart156.docx


Wednesday, August 21, 2024

 

Ownership:

When deployments become complex, the maintenance of their IaC calls for human resource allocations. While the are many factors that are significant to the planning of this allocation, one of the characteristics of the deployments is that there is repeated copy-and-paste involved across different deployment stamps. When a person is allowed to focus on one set of resources within a stamp in a subscription, there will be very little changes required to be made that avoid inadvertent errors made from copy and paste across subscriptions. Every resource is named with a convention and complex deployments increase the number of edits made across resources. When there is name variations introduced by the lines of business to differentiate deployment stamps and resources, even a modification of a resources across the subscription channels involves more copying than in the case when everything is self-contained within a subscription.

Another characteristic is that public cloud resource types require in-depth knowledge of how they work and some of them have sophisticated feature sets that it takes a while before a definition in the IaC for that resource type becomes the norm for deployment. It is in this regard that that cloud engineer expertise in certain resource types become a sought-after skill for many teams and a convenience for the infrastructure management team to consolidate and direct questions and support requests to the same group of individuals. Usually, two people can act as primary and secondary owners of these resource types. When the resource type is complex such as the use of analytics workspaces that come with their compute and storage ecosystem, designating pairs of individuals, if not more, can help with bringing industry and community perspectives to the team via trainings and conferences.

A third characteristic of working the public cloud deployments with IaC from the management’s point of view is the creation of active directory groups for individuals dedicated to working in owner, contributor and reader modes on deployments stamps and enabling the groups to be universal rather than global. The difference between groups created in these two modes is that one permits multi-domain environment access and changes to the membership trigger forest-wide replication which is helpful to ensure that permissions remain consistent across the forest. On-premises environments have traditionally used global groups since they are domain specific but with the migration to cloud resources, universal groups hold more appeal.

Securing access to resources via Active Directory groups also helps with the propagation of permissions and the ease of one-time registration to membership by individuals. When they leave, the access is automatically removed everywhere by the removal of membership and while this has remained true for most workplaces, it is even more pertinent when groups tend to be many for different purposes and creating well-known groups whose scope is tightly coupled to the resources they secure, help with less maintenance activities as individuals become empowered as needed to control the deployments of resources to the cloud.

 

References: 

Previous article in this series: IaCResolutionsPart156.docx