Thursday, March 31, 2022

Leetcode hard level: 1320. Minimum Distance to Type a Word Using Two Fingers

April 1, 2022 

1320. Minimum Distance to Type a Word Using Two Fingers

Here is the link. 


March 31, 2022
Introduction
There are so many things to learn from this hard level practice. What I did is to find a C# solution, and then try to run a simple test case, and see if I can understand the algorithm from this simple test case.

TLE error | 54/54 TLE error
I need to figure out how it is designed, and also there is TLE error to run against Leetcode online judge.

The following C# code passes online judge.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _1320_minimum_distance
{
    class Program
    {
        static void Main(string[] args)
        {
            var test = new Program();
            var result = test.MinimumDistance("CAKE");
        }
        
        /// <summary>
        /// study code:
        /// https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/discuss/478092/C-Solution-Top-down-DP-with-Memoization
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        public int MinimumDistance(string word)
        {
            int sum = 0;
            var result = int.MaxValue;
            var n = word.Length;
            
            var memo = new int[n, n];

            // How to analyze the following statements?
            // 
            for (int i = 0; i < n - 1; i++)
            {
                result = Math.Min(result, sum + calMinimumDistance(word, i, i + 1, memo));
                sum += calDistance(word[i], word[i + 1]);
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="word"></param>
        /// <param name="leftFinger"></param>
        /// <param name="rightFinger"></param>
        /// <param name="memo"></param>
        /// <returns></returns>
        private int calMinimumDistance(string word, int leftFinger, int rightFinger, int[,] memo)
        {
            int next = 1 + Math.Max(leftFinger, rightFinger);
            if (next == word.Length)
            {
                return 0;
            }

            if (memo[leftFinger, rightFinger] != 0)
            {
                return memo[leftFinger, rightFinger];
            }

            // think about two cases:
            // either left finger moves or right finger moves to word[next]
            // left finger - 
            // right finger -
            memo[leftFinger, rightFinger] = 
                Math.Min(calMinimumDistance(word, leftFinger, next, memo) + calDistance(word[rightFinger], word[next]),
                         calMinimumDistance(word, next, rightFinger, memo) + calDistance(word[leftFinger], word[next]));

            return memo[leftFinger, rightFinger];
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ch1"></param>
        /// <param name="ch2"></param>
        /// <returns></returns>
        private int calDistance(int ch1, int ch2)
        {
            int a = ch1 - 'A';
            var b = ch2 - 'A';
            // row distance + column distance
            return Math.Abs(a / 6 - b / 6) + Math.Abs(a % 6 - b % 6);
        }
    }
}

Breakfast and learn: Bigtable in action (Google Cloud Next '17)

Here is the link. 

19:38/ 55:07

Rows

  • updates are atomic - but only at the row level
  • store items related to a given entity in a single row
  • where atomic updates aren't needed and entity is large - then split it up
  • rows are sorted lexicographically by row-key
  • store related entities in adjacent rows
Row-key
  • determine a key strategy that facilitates common queries
  • choose keys that help distribute read/writes and avoids hotspots
  • avoid solely monotonically increasing keys (timestamp or sequence)
  • a combined-key strategy is helpful

Wednesday, March 30, 2022

Udemy course: The complete guide to becoming a software architect

Udemy purchase: System design | Behavior interview

March 30, 2022

I made another purchase of Udemy courses. 




Teva stock: More research | Plan to invest 3000 shares

March 30, 2022 

Florida population is 21,7million meaning it costed Teva 12,03 per capita to settle in Florida. Scaling to whole USA with 333million in population the total cost would be around 2,7billion in cash and 1,3billion in drugs (whole sale aquiciton cost) in 10-15 year period.

Udemy: System Design Fundamentals | Free course

 March 30, 2022

Here is the link.

Leetcode discuss: 1254. Number of Closed Islands

March 30, 2022

Here is the link. 


C# | DFS | Closed island | first row or last row or first column or last column

March 29, 2022
Problem statement:
Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.

Return the number of closed islands.

Closed islands | Find all nodes in one island | Determine if any node is on the border of matrix
Start from any node in given matrix with value 0, and run DFS search and visit all nodes in the same island, mark visited to set value as 1, and also check if the node is in the first row or last row or first column or last column. If there is one found, then the island is not a closed island.

The following statement is easy to follow, if island is closed then return true, do nothing. Otherwise check if the current row is the first or last row or current col is the first or last column.

 foundNotClosed = foundNotClosed || row == 0 || row == (rows - 1) || col == 0 || col == (columns - 1);

My first submission had an issue: index-out-of-range, runDFS function if statement col >= columns, but = is missing.

The following C# code passes online judge.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _1254_number_of_closed_islands
{
    class Program
    {
        static void Main(string[] args)
        {
            var test = new Program();
            var grid = new int[5][];
            grid[0] = new int[]{1,1,1,1,1,1,1,0};
             grid[1] = new int[]{1,0,0,0,0,1,1,0};
             grid[2] = new int[]{1,0,1,0,1,1,1,0};
             grid[3] = new int[]{1,0,0,0,0,1,0,1};
             grid[4] = new int[]{1,1,1,1,1,1,1,0};

             var count = test.ClosedIsland(grid);            
        }

        public int ClosedIsland(int[][] grid)
        {
            if (grid == null || grid.Length == 0 || grid[0].Length == 0)
                return 0;

            var rows = grid.Length;
            var columns = grid[0].Length;

            var count = 0;
            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < columns; col++)
                {
                    if (grid[row][col] == 1)
                        continue;

                    var foundNotClosed = false;

                    runDFS(grid, row, col, ref foundNotClosed);
                    if (!foundNotClosed)
                    {
                        count++;
                    }
                }
            }

            return count; 
        }

        private void runDFS(int[][] grid, int row, int col, ref bool foundNotClosed)
        {
            var rows = grid.Length;
            var columns = grid[0].Length;
            if (row < 0 || row >= rows || col < 0 || col >= columns || grid[row][col] == 1)
            {
                return; 
            }

            foundNotClosed = foundNotClosed || row == 0 || row == (rows - 1) || col == 0 || col == (columns - 1);

            grid[row][col] = 1;

            runDFS(grid, row, col + 1, ref foundNotClosed);
            runDFS(grid, row, col - 1, ref foundNotClosed);
            runDFS(grid, row - 1, col, ref foundNotClosed);
            runDFS(grid, row + 1, col, ref foundNotClosed);
        }
    }
}

Ameritrade IRA: TEVA position

 March 30, 2022

I have so many chances to invest and make gains on PSFE and AAL stocks, but I did not take enough risk to learn how to be top 1%. Since 99% will chase high price and fear the loss, it is important to purchase stocks and hold them wehn price was low like AAL this March around $12.75/ share, PSFE $2.75/ share in March, 2022

My position | Teva position | TEVA settles FL opiod case



Teva position in detail



Tuesday, March 29, 2022

Leetcode algorithms: Get back to practice | Warmup after one week break

March 29, 2022

Introduction

It is time for me to get back on Leetcode algorithms. I have one week break from March 21 to March 29, 2022. 

Get back to practice

I just worked on a few algorithms, and then I got back to practice again. I worked on Leetcode 767, 65, 791, 215. 


Leetcode profile | C# solution | Vote count: 2.5K | Study top 10 voted solutions

 https://leetcode.com/newbiecoder1/

Django (web framework)

 Django (/ˈæŋɡ/ JANG-goh; sometimes stylized as django)[6] is a Python-based free and open-source web framework that follows the model–template–views (MTV) architectural pattern.[7][8] It is maintained by the Django Software Foundation (DSF), an independent organization established in the US as a 501(c)(3) non-profit.

Django's primary goal is to ease the creation of complex, database-driven websites. The framework emphasizes reusability and "pluggability" of components, less code, low coupling, rapid development, and the principle of don't repeat yourself.[9] Python is used throughout, even for settings, files, and data models. Django also provides an optional administrative create, read, update and delete interface that is generated dynamically through introspection and configured via admin models.

Some well-known sites that use Django include Instagram,[10] Mozilla,[11] Disqus,[12] Bitbucket,[13] Nextdoor[14] and Clubhouse.[15]

CQRS Design Pattern in Microservices Architectures | Mehmet Özkaya | Udemy course

March 29, 2022

Here is the article. 

I like to copy content in the following, so I can read more carefully and freely highlight some content if needed. 

CQRS Design Pattern in Microservices Architectures


In this article, we are going to talk about Design Patterns of Microservices architecture which is The CQRS Design Pattern. As you know that we learned practices and patterns and add them into our design toolbox. And we will use these pattern and practices when designing e-commerce microservice architecture.


By the end of the article, you will learn where and when to apply CQRS Design Pattern into Microservices Architecture with designing e-commerce application system.

In this course, we’re going to learn how to Design Microservices Architecture with using Design Patterns, Principles and the Best Practices. We will start with designing Monolithic to Event-Driven Microservices step by step and together using the right architecture design patterns and techniques.

CQRS Design Pattern

CQRS is one of the important pattern when querying between microservices. We can use CQRS design pattern in order to avoid complex queries to get rid of inefficient joins. CQRS stands for Command and Query Responsibility Segregation. Basically this pattern separates read and update operations for a database.

Normally, in monolithic applications, most of time we have 1 database and this database should respond both query and update operations. That means a database is both working for complex join queries, and also perform CRUD operations. But if the application goes more complex this query and crud operations will be also is going to be un-manageable situation.

In example of reading database, if your application required some query that needs to join more than 10 table, this will lock the database due to latency of query computation. Also if we give example of writing database, when performing crud operations we would need to make complex validations and process long business logics, so this will cause to lock database operations.



So reading and writing database has different approaches that we can define different strategy to handle that operation. In order to that CQRS offers to use “separation of concerns” principles and separate reading database and the writing database with 2 database. By this way we can even use different database for reading and writing database types like using no-sql for reading and using relational database for crud operations.

Another consideration is we should understand our application use case behaviors, if our application is mostly reading use cases and not writing so much, we can say our application is read-incentive application. So we should design our architecture as per our reading requirements with focusing reading databases.

So we can say that CQRS separates reads and writes into different databases, Commands performs update data, Queries performs read data.

Commands should be actions with task-based operations like “add item into shopping cart” or “checkout order”. So commands can be handle with message broker systems that provide to process commands in async way.

Queries is never modify the database. Queries always return the JSON data with DTO objects. By this way, we can isolate the Commands and Queries.

In order to isolate Commands and Queries, it's best practice to separate read and write database with 2 databases physically. By this way, if our application is read-intensive that means reading more than writing, we can define custom data schema to optimize for queries.

Materialized view pattern is  agood example to implement reading databases. Because in this way we can avoid complex joins and mappings with pre-defined fine-grained data for query operations.


By this isolation, we can even use different databases for reading and writing database types like using no-sql document database for reading and using relational database for crud operations.

Instagram Database Architecture

This is so popular on microservices architecture also let me give an example of Instagram architecture. Instagram basically uses two database systems, one is relational database PostgreSQL and the other is no-sql database — Cassandra.



So that means Instagram uses no-sql Cassandra database for user stories that is read-incentive data. And using relational PostgreSQL database for User Information bio update. This is one of the examples of CRQS approaches.

How to Sync Databases with CQRS?

But when we separate read and write databases in 2 different databases, the main consideration is sync these two databases in a proper way.

So we should sync these 2 databases and keep sync always.

This can be solve by using Event-Driven Architecture. According to Event Driven Architecture, when something update in write database, it will publish an update event with using message broker systems and this will consume by the read database and sync data according to latest changes.

But this solution creates a consistency issue, because since we have implemented async communication with message brokers, the data would not be reflected immediately.



This will operate the principle of “eventual consistency”. The read database eventually synchronizes with the write database, and it can take some time to update read database in the async process. We discuss eventual consistency in the next section.

So if we come back to our read and write databases in CQRS pattern, When starting your design, you can take read database from replicas of write database. By this way we can use different read-only replicas with applying Materialized view pattern can significantly increase query performance.

Also when we separated read and write databases, it means we can scale them independently. That means if our application is read-incentive, I mean if it much more query that write, than we can scale only reading databases very fast.

CQRS comes with separating commands and query databases. So this required to sync both 2 databases with offering event-driven architectures. And with Event-driven architectures there are some new patterns and practice should be considered when applying CQRS.

Event Sourcing pattern is the first pattern we should consider to use with CQRS. Mostly CQRS is using with “Event Sourcing pattern” in Event-Driven Architectures. So after we have learned the CQRS we should learn “Event Sourcing pattern”, because CQRS and “Event Sourcing pattern” is the best practice to use both of them.

Design the Architecture — CQRS, Event Sourcing, Eventual Consistency, Materialized View

We are going to Design our e-commerce Architecture with applying CQRS Pattern.



Now We can Design our Ordering microservices databases

I am going to split 2 databases for Ordering microservices
1 for the write database for relational concerns
2 for the read database for querying concerns

So when user create or update an order, I am going to use relational write database, and when user query order or order history, I am going to use no-sql read database. and make consistent them when syncing 2 databases with using message broker system with applying publish/subscribe pattern.

Now we can consider tech stack of these databases,

I am going to use SQL Server for relational writing database, and using Cassandra for no-sql read database. Of course we will use Kafka for syncing these 2 database with pub/sub Kafka topic exchanges.

So we should evolve our architecture with applying other Microservices Data Patterns in order to accommodate business adaptations faster time-to-market and handle larger requests.

Microservices Distributed Caching | Udemy course | Mehmet Özkaya

 Here is the link. 

Microservices Distributed Caching

In this article, we are going to talk about Microservices Distributed Caching for Microservices Architectures. As you know that we learned practices and patterns and add them into our design toolbox. And we will use these pattern and practices when designing e-commerce microservice architecture.




By the end of the article, you will learn where and when to use Microservices Distributed Caching into Microservices Architecture with designing e-commerce application system.

Microservices Distributed Caching

We are going to talk about Microservices Caching. Caching is one of the important topic when you want your application faster.

Caching can increase performancescalability, and availability for microservices. The main idea is reducing latency with cache and makes application faster. When the number of requests are increased, caching will be really important for accommodating whole requests with high availability.

Reading data more than writing data | Caching | Julia's notes

If application request mostly comes for reading data that is not changes so frequently, then Caching will be so efficient. For example reading product catalog from e-commerce application can be cached in the architecture.

Caching also provide to avoid re-calculation processes. If one operations calculate by one server, then other application can consume calculated data from cache. In Microservices architectures are typically implement a distributed caching architecture.


Look at the above image. You can see that this is similar our microservice architecture. An API Gateway accommodate requests and invoke several internal backend microservices and aggregate them into 1 response.

So how we can increase the speed of this use case?

Of Course we should use The distributed cache. The distributed cache increases system responsiveness by returning cached data.

Separating the cache server from the microservices, cache services can be scaled up independently. <- read again

Additionally, separating the cache server from the microservices, gives ability to independently scale up cache services. This can be very useful when increased traffic of requests.

You can also use in-memory cache in our microservices, but it is not efficiency like distributed cache due to scalability issues. So now we can use distributed cache in our e-commerce design.

Design the Architecture — Microservices Distributed Caching

We are going to design our e-commerce application with the Microservices Distributed Caching. We will iterate the architecture design one by one as per requirements.




As you can see that now we have used Distributed Caching in our e-commerce architecture. Now lets decide to Technology Stack in this architecture.

Of course we should pick: Redis.

Redis, which stands for Remote Dictionary Server, is a fast, open-source, in-memory key-value data store for use as a database, cache, message broker, and queue. Redis is Fast, open source in-memory data store for use mostly as a database and cache. So its good to use Redis in our architecture.

So we should evolve our architecture with applying other Microservices Data Patterns in order to accommodate business adaptations faster time-to-market and handle larger requests.