Dinic's algorithm for Maximum Flow - GeeksforGeeks



Dinic's algorithm for Maximum Flow - GeeksforGeeks

Given a graph which represents a flow network where every edge has a capacity. Also given two vertices source 's' and sink 't' in the graph, find the maximum possible flow from s to t with following constraints :

  1. Flow on an edge doesn't exceed the given capacity of the edge.
  2. Incoming flow is equal to outgoing flow for every vertex except s and t.

Read full article from Dinic's algorithm for Maximum Flow - GeeksforGeeks


Program for Round Robin scheduling | Set 1 - GeeksforGeeks



Program for Round Robin scheduling | Set 1 - GeeksforGeeks

Round Robin is a CPU scheduling algorithm where each process is assigned a fixed time slot in a cyclic way.

  • It is simple, easy to implement, and starvation-free as all processes get fair share of CPU.
  • One of the most commonly used technique in CPU scheduling as a core.
  • It is preemptive as processes are assigned CPU only for a fixed slice of time at most.
  • The disadvantage of it is more overhead of context switching.


Read full article from Program for Round Robin scheduling | Set 1 - GeeksforGeeks


These Are The 16 Items That You Should Always Buy At Costco



These Are The 16 Items That You Should Always Buy At Costco

These Are The 16 Items That You Should Always Buy At Costco Sorry this article is not available in your chosen language. These Are The 16 Items That You Should Always Buy At Costco Costco is the best. I love to go there — sometimes even when I don't have anything to buy. I'm not gonna lie, sometimes I go there when I'm a little bit peckish and I walk around just eating samples. I know, I'm terrible person, but I doubt that I'm the only one that does this. In all seriousness, though, you can't beat the price. And Costco is the best place to go for school snacks when you have kids. When you are comparing price per ounce, Costco is the best place to buy these things. Depending on where you live, these prices may vary, but these were the best deals I could find. Advertisement 1. Kirkland pure maple syrup The Costco price on this stuff is 32.5¢ per ounce, beating out both Wal-Mart and Amazon. Plus, it's the best maple syrup I've ever had. 2.

Read full article from These Are The 16 Items That You Should Always Buy At Costco


Find first and last occurrences of an element in a sorted array - GeeksforGeeks



Find first and last occurrences of an element in a sorted array - GeeksforGeeks

Given a sorted array with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array.


Read full article from Find first and last occurrences of an element in a sorted array - GeeksforGeeks


codebytes: An algorithm to print all paths which sum to a given value in a Binary Tree.



codebytes: An algorithm to print all paths which sum to a given value in a Binary Tree.

An algorithm to print all paths which sum to a given value in a Binary Tree.

Q. You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum to a given value. The path does not need to start or end at the root or a leaf.

Algorithm:

1. Start at the root or any other node (if a node other than root is given).
2. Check all nodes to left and to right recursively, pass the running sum and a string representation of the path downwards.
3. If the sum equals the required value, store that path or print it.
4. Continue down until you hit a null. (We don't quit when running sum matches the required value as there may be negative value nodes down in the path and then a positive one or there maybe zero value nodes down in the tree which IS a possible path).

Read full article from codebytes: An algorithm to print all paths which sum to a given value in a Binary Tree.


Spring Boot Memory Performance



Spring Boot Memory Performance

It has sometimes been suggested that Spring and Spring Boot are "heavyweight", perhaps just because they allow apps to punch above their weight, providing a lot of features for not very much user code. In this article we concentrate on memory usage and ask if we can quantify the effect of using Spring? Specifically we would like to know more about the real overhead of using Spring compared to other JVM applications. We start by creating a basic application with Spring Boot, and look at a few different ways to measure it when it is running. Then we look at some comparison points: plain Java apps, apps that use Spring but not Spring Boot, an app that uses Spring Boot but no autoconfiguration, and some Ratpack sample apps.


Read full article from Spring Boot Memory Performance


Minimum number of equal amount bags to collect at least M money - GeeksforGeeks



Minimum number of equal amount bags to collect at least M money - GeeksforGeeks

Given unlimited number of coins of two denomination X and Y. Also given bags with capacity of N rupees, independent of number of coins. The task is to find the minimum number of bags such that each bag contains the same amount of rupees and sum of all the bags amount is at least M.


Read full article from Minimum number of equal amount bags to collect at least M money - GeeksforGeeks


Sum of product of x and y such that floor(n/x) = y - GeeksforGeeks



Sum of product of x and y such that floor(n/x) = y - GeeksforGeeks

Given a positive integer n. The task is to find the sum of product of x and y such that ⌊n/x⌋ = y (Integer Division).


Read full article from Sum of product of x and y such that floor(n/x) = y - GeeksforGeeks


Maximum number of groups of size 3 containing two type of items - GeeksforGeeks



Maximum number of groups of size 3 containing two type of items - GeeksforGeeks

Given n instance of item A and m instance of item B. Find the maximum number of groups of size 3 that can be formed using these items such that all groups contain items of both types, i.e., a group should not have either all items of type A or all items of type B.

Total number of items of type A in the formed groups must be less than or equal to n.
Total number of items of type B in the formed groups must be less than or equal to m.


Read full article from Maximum number of groups of size 3 containing two type of items - GeeksforGeeks


Maximum number of groups of size 3 containing two type of items - GeeksforGeeks



Maximum number of groups of size 3 containing two type of items - GeeksforGeeks

Given n instance of item A and m instance of item B. Find the maximum number of groups of size 3 that can be formed using these items such that all groups contain items of both types, i.e., a group should not have either all items of type A or all items of type B.

Total number of items of type A in the formed groups must be less than or equal to n.
Total number of items of type B in the formed groups must be less than or equal to m.


Read full article from Maximum number of groups of size 3 containing two type of items - GeeksforGeeks


Make two sets disjoint by removing minimum elements - GeeksforGeeks



Make two sets disjoint by removing minimum elements - GeeksforGeeks

Make two sets disjoint by removing minimum elements

Given two sets of integers as two arrays of size m and n. Find count of minimum numbers that should be removed from the sets so that both set become disjoint or don't contains any elements in common. We can remove elements from any set. We need to find minimum total elements to be removed.


Read full article from Make two sets disjoint by removing minimum elements - GeeksforGeeks


Maximum path sum in a triangle. - GeeksforGeeks



Maximum path sum in a triangle. - GeeksforGeeks

We have given numbers in form of triangle, by starting at the top of the triangle and moving to adjacent numbers on the row below, find the maximum total from top to bottom.


Read full article from Maximum path sum in a triangle. - GeeksforGeeks


Maximum and minimum sums from two numbers with digit replacements - GeeksforGeeks



Maximum and minimum sums from two numbers with digit replacements - GeeksforGeeks

Given two positive numbers calculate the minimum and maximum possible sums of two numbers. We are allowed to replace digit 5 with digit 6 and vice versa in either or both the given numbers.


Read full article from Maximum and minimum sums from two numbers with digit replacements - GeeksforGeeks


Technology Inheritance



Technology Inheritance

Someone once told me that people tend to move between companies using the flying wedge formation: a scout shows up to learn the culture and opportunities, and then an increasingly large contingent of previous coworkers and friends stream in.

This jives with my experience, likely the direct consequence of most hiring systems' heavy reliance on referrals (incidentally, I think what Slack is attempting to do to move their hiring pipeline away from referal dependence is one of the more interesting ideas in tech recruiting today).


Read full article from Technology Inheritance


Introduction to Architecting Systems for Scale



Introduction to Architecting Systems for Scale

Few computer science or software development programs attempt to teach the building blocks of scalable systems. Instead, system architecture is usually picked up on the job by working through the pain of a growing product or by working with engineers who have already learned through that suffering process.

In this post I'll attempt to document some of the scalability architecture lessons I've learned while working on systems at Yahoo! and Digg.

I've attempted to maintain a color convention for diagrams in this post:

  • green represents an external request from an external client (an HTTP request from a browser, etc),

Read full article from Introduction to Architecting Systems for Scale


My Experience: Problem solving techniques (Example problems) (Cont.)



My Experience: Problem solving techniques (Example problems) (Cont.)

In this post i will show you when to use graphs to solve specific type of problems. To know about graphs and other problem solving techniques you may need to read this.

Problem 14 (Shortest path)

Given a set of cities' paths represented as a two dimensional array grid where grid[i][j] = 1 iff there exists a path between city i to city j. Given two cities src and dst, find the shortest path to go from src to dst. If there is no such path return -1.

Solution // In this problem i will show you how to use BFS to get shortest path

Read full article from My Experience: Problem solving techniques (Example problems) (Cont.)


We Asked ICE About the Prank Calls to Their Anti-Immigrant Hotline and They Kind of Lost Their Shit



We Asked ICE About the Prank Calls to Their Anti-Immigrant Hotline and They Kind of Lost Their Shit

AP On Wednesday morning, the Immigration and Customs Enforcement agency unveiled an office called VOICE ( Victims of Immigration Crime Engagement ) dedicated to "the needs of crime victims and their families who have been impacted by crimes committed by removable criminal aliens." Advertisement By Thursday, VOICE's most prominent feature—a hotline through which people can call to learn, among other things, "additional criminal or immigration history may be available about an alien to victims or their families"—was swamped with prank calls reporting illegal aliens. As in alien aliens. And judging by the enraged email that ICE sent me when I asked for comment, the agency is supremely pissed off about it. The hoax crusade bubbled up on Twitter all day Wednesday. Adding to the frenzy was the fact that VOICE's launch date of April 26 was also " Alien Day "—a reference to the moon featured in James Cameron's 1986 classic, Aliens ( LV-426 . Get it?).

Read full article from We Asked ICE About the Prank Calls to Their Anti-Immigrant Hotline and They Kind of Lost Their Shit


How to Find a Solution – topcoder



How to Find a Solution – topcoder

With many topcoder problems, the solutions may be found instantly just by reading their descriptions. This is possible thanks to a collection of common traits that problems with similar solutions often have. These traits serve as excellent hints for experienced problem solvers that are able to observe them. The main focus of this article is to teach the reader to be able to observe them too.

Straight-forward problems that don't require any special technique (e.g. simulation, searching, sorting etc.)
In most cases, these problems will ask you to perform some step by step, straight-forward tasks. Their constraints are not high, and not too low. In most cases the first problems (the easiest ones) in topcoder Single Rounds Matches are of this kind. They test mostly how fast and properly you code, and not necessarily your algorithmic skills.


Read full article from How to Find a Solution – topcoder


GOOGL Stock: Alphabet Inc (GOOGL) Stock Couldn't Sink Itself if It Tried | InvestorPlace



GOOGL Stock: Alphabet Inc (GOOGL) Stock Couldn't Sink Itself if It Tried | InvestorPlace

Breaking news sponsored by Alphabet Inc (GOOGL) Couldn't Sink Itself if It Tried Guarantees don't exist on Wall Street, but GOOGL stock comes really close By Josh Enomoto , InvestorPlace Contributor  |   Apr 26, 2017, 11:40 am EDT Get GOOGL alerts: Popular Posts: Recent Posts: Alphabet has proven, perhaps more than any other company in the world, that accomplishment is indeed a journey. A cursory look at GOOGL stock will settle the deal for most folks. Beyond that, InvestorPlace contributor Dana Blankenhorn hit the nail on the head when he discussed Alphabet Inc's success. They kept it simple, and "focused on what computers do ." On the flip side, Yahoo! Inc. (NASDAQ: YHOO ) did not take that advice to heart. Frankly, the results speak for themselves. Although YHOO's lifetime returns are 3,400%, when you compare it to its internet-bubble peak, shares are down 55%. Comparatively, GOOGL stock is up over 1,500% lifetime — and it keeps going and going and going.

Read full article from GOOGL Stock: Alphabet Inc (GOOGL) Stock Couldn't Sink Itself if It Tried | InvestorPlace


java - Refreshing Caches while under load with Spring/EHCache - Stack Overflow



java - Refreshing Caches while under load with Spring/EHCache - Stack Overflow

There are two Ehcache provided constructs that could help you:

  1. Refresh ahead
  2. Scheduled refresh

Both require you to change the way you interact with your cache as they require a CacheLoader to be configured.

Unfortunately, I can't find online documentation that shows example for the second option. It allows to refresh cache entries using Quartz to schedule it. It can also refresh only a subset of the keys, based on a key generator. Have a look at classes in package net.sf.ehcache.constructs.scheduledrefresh


Read full article from java - Refreshing Caches while under load with Spring/EHCache - Stack Overflow


Crack the System Design Interview - Puncsky CS Notebook



Crack the System Design Interview - Puncsky CS Notebook

1.3 Step 3. Discuss individual components and how they interact in detail

When we truly understand a system, we should be able to identify what each component is and explain how they interact with one another. Take these components in the above diagram and specify each one by one. This could lead to more general discussions, such as the three common topics in Section 2, and to more specific domains, like how to design the photo storage data layout

1.3.1 Load Balancer

Generally speaking, load balancers fall into three categories:

  • DNS Round Robin (rarely used): clients get a randomly-ordered list of IP addresses.
    • pros: easy to implement and free
    • cons: hard to control and not responsive, since DNS cache needs time to expire
  • L3/L4 Load Balancer: traffic is routed by IP address and port. L3 is network layer (IP). L4 is session layer (TCP).
    • pros: better granularity, simple, responsive
  • L7 Load Balancer: traffic is routed by what is inside the HTTP protocol. L7 is application layer (HTTP).

It is good enough to talk in this level of detail on this topic, but in case the interviewer wants more, we can suggest exact algorithms like round robin, weighted round robin, least loaded, least loaded with slow start, utilization limit, latency, cascade, etc.


Read full article from Crack the System Design Interview - Puncsky CS Notebook


Building Microservices? Here is what you should know | cloudncode



Building Microservices? Here is what you should know | cloudncode

Just to refresh our memories, micro service architecture is an evolution of the SOA architecture, whereas SOA was focused on integration of various applications, Micro services architecture (MSA) aims to create small modular services which belong to a single application.

MSA came to the forefront with the advent of high speed computing (lowered latencies) and the continuously growing need of continuous deployment and integration.

One other major advantage with MSA and often overlooked is that now independent services can be written and re-written in different languages which is best suited for the service, or just because it has too much bloat which would otherwise spark off a multi-year re-write project… and we all know where that leads us.

Wait…what has CI or CD to do with MSA?

With MSA as we inherently get modular services broken by functionality, we can make changes inside one and deploy it with peace of mind knowing that it will not effect any other service as long as the external interface (API contract) is not modified. The latter fact allows us to scale, lower significantly the time to production (lower scope of testing) and fail fast.


Read full article from Building Microservices? Here is what you should know | cloudncode


caching - Configuring redis to consistently evict older data first - Stack Overflow



caching - Configuring redis to consistently evict older data first - Stack Overflow

up vote 28 down vote accepted

AFAIK, it is not possible to configure Redis to consistently evict the older data first.

When the *-ttl or *-lru options are chosen in maxmemory-policy, Redis does not use an exact algorithm to pick the keys to be removed. An exact algorithm would require an extra list (for *-lru) or an extra heap (for *-ttl) in memory, and cross-reference it with the normal Redis dictionary data structure. It would be expensive in term of memory consumption.

With the current mechanism, evictions occur in the main event loop (i.e. potential evictions are checked at each loop iteration before each command is executed). Until memory is back under the maxmemory limit, Redis randomly picks a sample of n keys, and selects for expiration the most idle one (for *-lru) or the one which is the closest to its expiration limit (for *-ttl). By default only 3 samples are considered. The result is non deterministic.

One way to increase the accuracy of this algorithm and mitigate the problem is to increase the number of considered samples (maxmemory-samples parameter in the configuration file). Do not set it too high, since it will consume some CPU. It is a tradeoff between eviction accuracy and CPU consumption.

Now if you really require a consistent behavior, one solution is to implement your own eviction mechanism on top of Redis. For instance, you could add a list (for non updatable keys) or a sorted set (for updatable keys) in order to track the keys that should be evicted first. Then, you add a daemon whose purpose is to periodically check (using INFO) the memory consumption and query the items of the list/sorted set to remove the relevant keys.

Please note other caching systems have their own way to deal with this problem. For instance with memcached, there is one LRU structure per slab (which depends on the object size), so the eviction order is also not accurate (although more deterministic than with Redis in practice).


Read full article from caching - Configuring redis to consistently evict older data first - Stack Overflow


A Word on Scalability - All Things Distributed



A Word on Scalability - All Things Distributed

Scalability is frequently used as a magic incantation to indicate that something is badly designed or broken. Often you hear in a discussion "but that doesn't scale" as the magical word to end an argument. This is often an indication that developers are running into situations where the architecture of their system limits their ability to grow their service. If scalability is used in a positive sense it is in general to indicate a desired property as in "our platform needs good scalability".


Read full article from A Word on Scalability - All Things Distributed


多米诺骨牌 - 每天一道算法题 - SegmentFault



多米诺骨牌 - 每天一道算法题 - SegmentFault

100张多米诺骨牌整齐地排成一列,按顺序编号为1、2、3、4……99、100。第一次拿走所有的奇数位置上的骨牌,第二次再从剩余的骨牌中拿走所有奇数位置上的骨牌,依次类推,请问最后剩下的一张骨牌的编号是多少()

A.48
B.50
C.52
D.64

正确答案:D.

答对了吗?答对了吗?答对了吗?

来一波解析给大家吧:

第一次拿走多米诺骨牌我们剩下:2,4,6,8,10...均为2的倍数。

第二次拿走多米诺骨牌我们剩下4,8,12,16....均为4的倍数。

第三次拿走多米诺骨牌我们剩下,8,16,24...均为8的倍数。

那么聪明的我们发现了规律:每次剩下的都是2的n次方的倍数。2的n次方小于100的最大值是什么?

2的6次方,也就是64,所以选择答案D。

换种直观的方法:
我们不考虑什么剩下的数究竟是多少,我们只知道剩下的数是偶数,而且个数我们是清楚的,所以就有:

第一次后剩下50个偶数
将它们除以2得到1~50的一列
第二次后剩下25个偶数 2 4 6...50
将他们除以2得到1~25的一列
第三次后剩下12个偶数 2 4 5...24
将他们除以2得到1~12的一列
同理,第四次除后到6 第五次除后到3 第六次除后剩下最后一张1
所以,它的编号是1×2^6=64


Read full article from 多米诺骨牌 - 每天一道算法题 - SegmentFault


AI Game Playing – Zeesun – Medium



AI Game Playing – Zeesun – Medium

Type of AI problems

  • Fully Observable vs Partially Observable
  • Deterministic vs Stochastic
  • Discrete vs Continuous
  • Benign (only one person is taking action) vs Adversarial

Minimax Algorithm

  • Choose a winning strategy. In an isolation game, the winning strategy can be maximizing the possible moves at each level of the game tree.
  • At each level of the game tree, it is assumed that player will choose the branch that maximizes the benefits (opponent will choose a branch to minimize the effect of the winning strategy)

Branching Factor

  • how many branches each node will have on average

Depth-Limited Search

  • Using the branch factor and the limitation of the number of nodes can be searched every turn, we can determine how deep the search can go

Quiescent Search

  • If the decision varies a lot at two neighbor levels, that means a critical decision is made between those two levels
  • Thus, we will use quiescent search to search deeper

Iterative Deepening

  • After finishing searching depth N, then researching the tree with depth N+1
  • Since time complexity is dominated by the last level search, iterative deepening will not increase time complexity compared to regular search

Horizon Effect

  • Choices that are obvious to human beings might not be obvious for AI

Alpha Beta Pruning

  • adversarial search algorithm, which seeks to decrease the number of nodes in the search tree.
  • Improve efficiency
  • It does not work well with multi-players

Thad's Asides

  • AI = Clever Solutions to Exponential Problems

Read full article from AI Game Playing – Zeesun – Medium


Facebook HR 内部邮件, System Design 面试内容揭秘!



Facebook HR 内部邮件, System Design 面试内容揭秘!

首先,HR指出,Facebook 的 System Design 面试时长为45分钟,主要考察是是,求职者能否处理 Large Scale 的问题。在面试过程中,面试官会让你为Facebook设计一个feature。通过设计一个负责的系统,面试官主要是想考察你在 consistency, availability 和 partition tolerance 之间如何做 tradeoff,进而评估你的思考、实践能力。在这里,Facebook HR 着重要求面试者,一定要看以下的资料


Read full article from Facebook HR 内部邮件, System Design 面试内容揭秘!


Integrating Your Catalog with Fire TV - Amazon Apps & Services Developer Portal



Integrating Your Catalog with Fire TV - Amazon Apps & Services Developer Portal

Integrating your media catalog with Amazon Fire TV allows your content to be discovered and launched from the Fire TV home screen. Catalog Integration has two major components:

  • A catalog file that specifies the movies and TV shows that you offer through your app.
  • Integration between your app and the Fire TV Home Screen Launcher, which enables users to play your content directly from search and browse results.

Catalog Integration allows your content to be included in the results of a search performed from the Fire TV home screen. It also allows a user to find your content while browsing Fire TV outside of your app, such as when browsing by genre (also known as "universal browse and search"). Regardless of where in the Fire TV UI users find your content, they can play it directly without needing to open your app first.


Read full article from Integrating Your Catalog with Fire TV - Amazon Apps & Services Developer Portal


Sharding & IDs at Instagram – Instagram Engineering



Sharding & IDs at Instagram – Instagram Engineering

With more than 25 photos and 90 likes every second, we store a lot of data here at Instagram. To make sure all of our important data fits into memory and is available quickly for our users, we've begun to shard our data — in other words, place the data in many smaller buckets, each holding a part of the data.

Our application servers run Django with PostgreSQL as our back-end database. Our first question after deciding to shard out our data was whether PostgreSQL should remain our primary data-store, or whether we should switch to something else. We evaluated a few different NoSQL solutions, but ultimately decided that the solution that best suited our needs would be to shard our data across a set of PostgreSQL servers.

Before writing data into this set of servers, however, we had to solve the issue of how to assign unique identifiers to each piece of data in the database (for example, each photo posted in our system). The typical solution that works for a single database — just using a database's natural auto-incrementing primary key feature — no longer works when data is being inserted into many databases at the same time. The rest of this blog post addresses how we tackled this issue.


Read full article from Sharding & IDs at Instagram – Instagram Engineering


Netty工具类HashedWheelTimer源码走读(一) - 不经年,知不足



Netty工具类HashedWheelTimer源码走读(一) - 不经年,知不足

    可以看到, HashedWheelTimer 主要用来高效处理大量定时任务,  且任务对时间精度要求相对不高,  比如链接超时管理等场景, 缺点是,  内存占用相对较高.


Read full article from Netty工具类HashedWheelTimer源码走读(一) - 不经年,知不足


定时任务调度器 · 系统设计(System Design)



定时任务调度器 · 系统设计(System Design)

请实现一个定时任务调度器,有很多任务,每个任务都有一个时间戳,任务会在该时间点开始执行。

+

定时执行任务是一个很常见的需求,所以这题也是从实践中提炼出来的,做好了将来说不定能用上。

+

仔细分析一下,这题可以分为三个部分:

+

  • 优先队列。因为多个任务需要按照时间从小到大排序,所以需要用优先队列。
  • 生产者。不断往队列里塞任务。
  • 消费者。如果队列里有任务过期了,则取出来执行该任务。

Read full article from 定时任务调度器 · 系统设计(System Design)


算法珠玑 · GitBook



算法珠玑 · GitBook

本书的目标读者是准备去硅谷找工作的码农,也适用于在国内找工作的码农,以及刚接触ACM算法竞赛的新手。

市场上讲解算法的书已经汗牛充栋,为什么还要写这本书呢?主要原因是我对目前市场上的大部分算法书都不太满意。 本书有如下特色:

  1. 背后有强大的AlgoHub支持。

    本书的所有题目,都可以在 www.algohub.org(即将上线) 上在线判断代码。这样的一大好处是,读者可以边看书,边实现自己的代码,然后提交到网站上验证自己的想法是否正确。AlgoHub的使命是成为最好的算法学习和交流平台。AlgoHub囊括了 POJ, ZOJ, leetcode, HackerRank 等网站的经典题目(一些质量不高的题目则忽略),且 AlgoHub有非常简单的加题系统,用户不需要写一行代码即可自己添加题目,所以AlgoHub的题库还在飞速增长中。

  2. 每道题都有完整的代码。

    市场上的大部分书,都会讲思路,但给出的代码都是片段,不是完整可编译的代码。本书每题都有完整的代码,且每个代码经过千锤百炼,保证可读性的前提下尽可能简短,方面读者在面试中能快速写出来。

  3. 每道题都有多种解法。

    本书的宗旨是,用尽可能少的题目,覆盖尽可能多的算法。本书中的的每道题都有多种解法,每种解法不是简单的小改进,而是完全不同的思路,力求举一反三,让读者触类旁通。


Read full article from 算法珠玑 · GitBook


Detect Duplicate Subtrees in a Binary Tree



Detect Duplicate Subtrees in a Binary Tree

Often in our life we study Data Structures and Algorithms, it can be for a course, interview or just for fun. I personally like to solve interview questions related to trees. I came across a google interview question on careercup.com "Find if a given binary tree has duplicate subtrees"


Read full article from Detect Duplicate Subtrees in a Binary Tree


Program for Best Fit algorithm in Memory Management - GeeksforGeeks



Program for Best Fit algorithm in Memory Management - GeeksforGeeks

Best fit allocates the process to a partition which is the smallest sufficient partition among the free available partitions.


Read full article from Program for Best Fit algorithm in Memory Management - GeeksforGeeks


strictfp keyword in java - GeeksforGeeks



strictfp keyword in java - GeeksforGeeks

strictfp is a keyword in java used for restricting floating-point calculations and ensuring same result on every platform while performing operations in the floating-point variable.
Floating point calculations are platform dependent i.e. different output(floating-point values) is achieved when a class file is run on different platforms(16/32/64 bit processors). To solve this types of issue, strictfp keyword was introduced in JDK 1.2 version by following IEEE 754 standards for floating-point calculations.


    Read full article from strictfp keyword in java - GeeksforGeeks


    Jacoco report aggregation for code coverage - PrismoSkills



    Jacoco report aggregation for code coverage - PrismoSkills

    Jacoco is a an awesome tool for getting the code coverage stats of your project.
    Using jacoco's maven plugin, we can generate the code coverage report in just a few lines of pom.xml code.

    In this section, we cover how to use the report-aggregate goal to generate coverage reports when the tests are in a separate submodule and the code they test is in some other sibling submodules. Consider the following project structure:

    Read full article from Jacoco report aggregation for code coverage - PrismoSkills


    Check if a string can be obtained by rotating another string 2 places - GeeksforGeeks



    Check if a string can be obtained by rotating another string 2 places - GeeksforGeeks

    Given two strings, the task is to find if a string can be obtained by rotating another string two places.

    Read full article from Check if a string can be obtained by rotating another string 2 places - GeeksforGeeks


    HackerRank Solution: Even Tree | HackerRank Tutorials



    HackerRank Solution: Even Tree | HackerRank Tutorials

    You are given a tree (a simple connected graph with no cycles). The tree has N nodes numbered from 1 to N.

    Find the maximum number of edges you can remove from the tree to get a forest such that each connected component of the forest contains an even number of vertices.

    Input Format:

    The first line of input contains two integers N and M. N is the number of vertices, and M is the number of edges. 
    The next M lines contain two integers ui and vi which specifies an edge of the tree.


    Read full article from HackerRank Solution: Even Tree | HackerRank Tutorials


    Generators of finite cyclic group under addition - GeeksforGeeks



    Generators of finite cyclic group under addition - GeeksforGeeks

    Given a number n, find all generators of cyclic additive group under modulo n. Generator of a set {0, 1, … n-1} is an element x such that x is smaller than n, and using x (and addition operation), we can generate all elements of the set.


    Read full article from Generators of finite cyclic group under addition - GeeksforGeeks


    Find the element that appears once in an array where every other element appears twice - GeeksforGeeks



    Find the element that appears once in an array where every other element appears twice - GeeksforGeeks

    Given an array of integers. All numbers occur twice except one number which occurs once. Find the number in O(n) time & constant extra space.


    Read full article from Find the element that appears once in an array where every other element appears twice - GeeksforGeeks


    Dynamic Method Dispatch or Runtime Polymorphism in Java - GeeksforGeeks



    Dynamic Method Dispatch or Runtime Polymorphism in Java - GeeksforGeeks

    1. Dynamic method dispatch allow Java to support overriding of methods which is central for run-time polymorphism.
    2. It allows a class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods.
    3. It also allow subclasses to add its specific methods subclasses to define the specific implementation of some.

    Static vs Dynamic binding

    • Static binding is done during compile-time while dynamic binding is done during run-time.
    • private, final and static methods and variables uses static binding and bonded by compiler while overridden methods are bonded during runtime based upon type of runtime object


    Read full article from Dynamic Method Dispatch or Runtime Polymorphism in Java - GeeksforGeeks


    Sort 3 Integers without using if condition or using only max() function - GeeksforGeeks



    Sort 3 Integers without using if condition or using only max() function - GeeksforGeeks

    Given three inte­gers, print them in sorted order with­out using if condition.


    Read full article from Sort 3 Integers without using if condition or using only max() function - GeeksforGeeks


    Number of subsequences of the form a^i b^j c^k - GeeksforGeeks



    Number of subsequences of the form a^i b^j c^k - GeeksforGeeks

    Given a string, count number of subsequences of the form aibjck, where i >= 1, j >=1 and k >= 1.

    Note: Two subsequences are considered different if the set of array indexes picked for the 2 subsequences are different.

    Expected Time Complexity : O(n)


    Read full article from Number of subsequences of the form a^i b^j c^k - GeeksforGeeks


    Buffer Overflow Attack with Example - GeeksforGeeks



    Buffer Overflow Attack with Example - GeeksforGeeks

    A buffer is a temporary area for data storage. When more data (than was originally allocated to be stored) gets placed by a program or system process, the extra data overflows. It causes some of that data to leak out into other buffers, which can corrupt or overwrite whatever data they were holding.

    In a buffer-overflow attack, the extra data sometimes holds specific instructions for actions intended by a hacker or malicious user; for example, the data could trigger a response that damages files, changes data or unveils private information.


    Read full article from Buffer Overflow Attack with Example - GeeksforGeeks


    random header in C++ | Set 1(Generators) - GeeksforGeeks



    random header in C++ | Set 1(Generators) - GeeksforGeeks

    This header introduces random number generation facilities. This library allows to produce random numbers using combinations of generators and distributions.


    Read full article from random header in C++ | Set 1(Generators) - GeeksforGeeks


    Yong Ouyang: Solving Farmer-Wolf-Goat-Cabbage riddle with Groovy/Java



    Yong Ouyang: Solving Farmer-Wolf-Goat-Cabbage riddle with Groovy/Java

    A farmer is on the west bank of a river with a wolf, a goat and a cabbage in his care. Without his presence the wolf would eat the goat or the goat would eat the cabbage. The wolf is not interested in the cabbage. The farmer wishes to bring his three charges across the river. However the boat available to him can only carry one of the wolf, goat and cabbage besides himself. The puzzle is: is there a sequence of river crossings so that the farmer can transfer himself and the other three all intact to the east bank?
  • The Solution
  • It is a task that given an initial state, a final state, and a set of rules, one will start from the initial state and try to reach to the final state by passing through some intermediate states. Each move will transform from one state to the other, and there might be multiple valid moves from a given state. Such a collection of interconnected states can be represented by State Space Graph.
    Let's use 'f', 'c', 'g', 'w' to denote the farmer, the cabbage, the goat, and the wolf, and use '|' to separate the river where left of the '|' denotes west bank and right of the '|' denotes east bank. Initially, they are all at the west bank of the river, which is represented as 'fcgw |' as shown below. We can solve the riddle by figuring out what the possible and valid moves are, using either Breadth-First Search or Depth-First Search, on a state space graph shown below

    Read full article from Yong Ouyang: Solving Farmer-Wolf-Goat-Cabbage riddle with Groovy/Java


    Zombie Processes and their Prevention - GeeksforGeeks



    Zombie Processes and their Prevention - GeeksforGeeks

    Zombie state : When a process is created in UNIX using fork() system call, the address space of the Parent process is replicated. If the parent process calls wait() system call, then the execution of parent is suspended until the child is terminated. At the termination of the child, a 'SIGCHLD' signal is generated which is delivered to the parent by the kernel. Parent, on receipt of 'SIGCHLD' reaps the status of the child from the process table. Even though, the child is terminated, there is an entry in the process table corresponding to the child where the status is stored. When parent collects the status, this entry is deleted. Thus, all the traces of the child process are removed from the system. If the parent decides not to wait for the child's termination and it executes its subsequent task, then at the termination of the child, the exit status is not read. Hence, there remains an entry in the process table even after the termination of the child. This state of the child process is known as the Zombie state.


    Read full article from Zombie Processes and their Prevention - GeeksforGeeks


    Print all full nodes in a Binary Tree - GeeksforGeeks



    Print all full nodes in a Binary Tree - GeeksforGeeks

    Given a binary tree, print all nodes will are full nodes. Full Nodes are nodes which has both left and right children as non-empty.


    Read full article from Print all full nodes in a Binary Tree - GeeksforGeeks


    March for Science draws big crowds across U.S. | Reuters



    March for Science draws big crowds across U.S. | Reuters

    March for Science draws big crowds across U.S. By Lacey Johnson | WASHINGTON WASHINGTON Thousands of scientists and people from other walks of life turned out in Washington and New York on Saturday for Earth Day events that organizers have framed as a "celebration" of science to counter a growing disregard for evidence-based knowledge. The "March for Science" festivities included "teach-ins" on the National Mall and parades in midtown Manhattan and hundreds of other cities and towns. The events were non-partisan, according to organizers, aimed at reaffirming "the vital role science plays in our democracy," according to the march's website. Still, the marches were effectively protests against steep cuts that President Donald Trump has proposed for federal science and research budgets and his administration's skepticism about climate change and the need to slow global warming. "It's important to show this administration that we care about facts," said Chris Taylor, 24,

    Read full article from March for Science draws big crowds across U.S. | Reuters


    The prisoner's dilemma in Game theory - GeeksforGeeks



    The prisoner's dilemma in Game theory - GeeksforGeeks

    This is the dilemma both the prisoner's face. Should one cooperate or betray?
    Even if the best solution would be both the prisoners cooperating with each other but due to uncertainty on each other both of them betray each other getting a lesser optimum solution.
    This can be observed in may real-life cases like:

    • A pair working on a project. You do best if your competitor does all the work, since you get the same grade. But if neither of you do the work, you both fail.
    • Advertising. If both companies spend money on advertising, their market share won't change from if neither does. But if one company outspends the other, they will receive a benefit.


    Read full article from The prisoner's dilemma in Game theory - GeeksforGeeks


    Count Divisors of n in O(n^1/3) - GeeksforGeeks



    Count Divisors of n in O(n^1/3) - GeeksforGeeks

    Given a number n, count all distinct divisors of it.


    Read full article from Count Divisors of n in O(n^1/3) - GeeksforGeeks


    Move all occurrences of an element to end in a linked list - GeeksforGeeks



    Move all occurrences of an element to end in a linked list - GeeksforGeeks

    Given a linked list and a key in it, the task is to move all occurrences of given key to end of linked list, keeping order of all other elements same.


    Read full article from Move all occurrences of an element to end in a linked list - GeeksforGeeks


    Double Pointer (Pointer to Pointer) in C - GeeksforGeeks



    Double Pointer (Pointer to Pointer) in C - GeeksforGeeks

    We already know that a pointer points to a location in memory and thus used to store address of variables. So, when we define a pointer to pointer. The first pointer is used to store the address of second pointer. That is why they are also known as double pointers.


    Read full article from Double Pointer (Pointer to Pointer) in C - GeeksforGeeks


    LeetCode 简略题解 - 401~500 - 知乎专栏



    LeetCode 简略题解 - 401~500 - 知乎专栏

    解法2:这个解法很巧妙,我鼓捣了一个多钟头才想明白。首先,这题除了O(N ^ 2)的暴力解法,肯定有更高效的解法。为什么?因为这是个关于"排序"的问题,你们都知道O(N * logN)是比较排序的下界。而且这题涉及到了数数。所以,我决定用树状数组试试,结果还真搞出来了。虽然实际复杂度不是O(N * logN),而是O(N * log ^2 N)。但总体的思想,还是二分搜索。用树状数组,只是为了区间求和。


    Read full article from LeetCode 简略题解 - 401~500 - 知乎专栏


    Multiples of 3 and 5 without using % operator - GeeksforGeeks



    Multiples of 3 and 5 without using % operator - GeeksforGeeks

    Write a short program that prints each number from 1 to n on a new line.

    1. For each multiple of 3, print "Multiple of 3" instead of the number.
    2. For each multiple of 5, print "Multiple of 5" instead of the number.
    3. For numbers which are multiples of both 3 and 5, print "Multiple of 3. Multiple of 5." instead of the number.


    Read full article from Multiples of 3 and 5 without using % operator - GeeksforGeeks


    Understanding OutOfMemoryError



    Understanding OutOfMemoryError

    In Java, all objects are stored in the heap. They are allocated by the new operator, and discarded when the JVM determines that no program thread can access them. Most of the time, this happens quietly, and programmers don't give it a second thought. And then, usually a day or so before a deadline, the program dies.

    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

    OutOfMemoryError is a frustrating exception. It usually means that you're doing something wrong: either holding onto objects too long, or trying to process too much data at a time. Sometimes, it indicates a problem that's out of your control, such as a third-party library that caches strings, or an application server that doesn't clean up after deploys. And sometimes, it has nothing to do with objects on the heap.

    This article looks at the different causes of OutOfMemoryError, and what you can do about them. It focuses on the Sun JVM, which is the one that I use. However, much of the material applies to any JVM implementation. It is written based on literature available online and my own experience. I don't work on the JVM internals, so can't speak from a position of authority. But I have faced — and fixed — a lot of memory problems.


    Read full article from Understanding OutOfMemoryError


    Defanging the OutOfMemoryError | Delphix



    Defanging the OutOfMemoryError | Delphix

    Specifically, your application "wishes to hold the whole sky" and it's failing intermittently because it's running out of memory. You can't find the issue and your customers are growing impatient. How do you defuse the situation? I was inspired to write this post by a recent bug we fixed, where our core infrastructure team worked on a problem involving the Java heap, the garbage collector, Java Native Access (JNA), native memory allocations, and even segfaults! It is an attempt to detail all of the debugging tools and techniques we use to root cause OutOfMemoryErrors, and some approaches for fixing them. My hope is that publishing our playbook on OutOfMemoryErrors will help others solve tough Java memory allocation issues with less effort and discovery than it's taken us to get where we are today. Although it's specifically written about the Oracle JVM for Java 7 running on a Unix operating system, most of the tools I describe are available or have a 1:1 replacement in other JVMs and OSes. The high-level concepts and techniques even apply to garbage collected languages that don't run on the JVM, but you'll have to do a bit more mental translation.


    Read full article from Defanging the OutOfMemoryError | Delphix


    Netty.docs: Native transports



    Netty.docs: Native transports

    Since 4.0.16, Netty provides the native socket transport for Linux using JNI. This transport has higher performance and produces less garbage, so you might want to give it a try.

    Using the native transport

    Because the native transport is compatible with the NIO transport, you can just do the following search-and-replace:

    • NioEventLoopGroupEpollEventLoopGroup
    • NioEventLoopEpollEventLoop
    • NioServerSocketChannelEpollServerSocketChannel
    • NioSocketChannelEpollSocketChannel

    Read full article from Netty.docs: Native transports


    [KAFKAC-9] java.lang.OutOfMemoryError: Direct buffer memory - Couchbase



    [KAFKAC-9] java.lang.OutOfMemoryError: Direct buffer memory - Couchbase

    when the connector is running, memory keeps decreasing, even when there is no document to produce, it stills eating up the memory till it crashed


    Read full article from [KAFKAC-9] java.lang.OutOfMemoryError: Direct buffer memory - Couchbase


    Cassandra driver error when starting Cassandra microsevice with docker-compose file · Issue #3428 · jhipster/generator-jhipster · GitHub



    Cassandra driver error when starting Cassandra microsevice with docker-compose file · Issue #3428 · jhipster/generator-jhipster · GitHub

    When starting a Cassandra microservice with the docker-compose generated files, the following warning and stack trace appears in the log:


    Read full article from Cassandra driver error when starting Cassandra microsevice with docker-compose file · Issue #3428 · jhipster/generator-jhipster · GitHub


    Netty3 masks OutOfMemoryError: Direct buffer memory · Issue #6005 · netty/netty



    Netty3 masks OutOfMemoryError: Direct buffer memory · Issue #6005 · netty/netty

    We're not setting any limits on direct memory size, so it probably happens because the machine is low on OS memory. However, netty catches this exception, and continues like everything is normal, but Elasticsearch is in a weird state.


    Read full article from Netty3 masks OutOfMemoryError: Direct buffer memory · Issue #6005 · netty/netty


    Check if frequency of all characters can become same by one removal - GeeksforGeeks



    Check if frequency of all characters can become same by one removal - GeeksforGeeks

    Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string.

    Read full article from Check if frequency of all characters can become same by one removal - GeeksforGeeks


    Find number of endless points - GeeksforGeeks



    Find number of endless points - GeeksforGeeks

    Given a binary N x N matrix, we need to find the total number of matrix positions from which there is an endless path. Any position (i, j) is said to have an endless path if and only if all of the next positions in its row(i) and its column(j) should have value 1. If any position next to (i,j) either in row(i) or in column(j) will have 0 then position (i,j) doesn't have any endless path.


    Read full article from Find number of endless points - GeeksforGeeks


    Find the first repeated character in a string - GeeksforGeeks



    Find the first repeated character in a string - GeeksforGeeks

    Given a string, find the first repeated character in it. We need to find the character that occurs more than once and whose index of first occurrence is smallest.

    Read full article from Find the first repeated character in a string - GeeksforGeeks


    Using else conditional statement with for loop in python - GeeksforGeeks



    Using else conditional statement with for loop in python - GeeksforGeeks

    Such type of else is useful only if there is an if condition present inside the loop which somehow depends on the loop variable.

    In the following example, the else statement will only be executed if no element of the array is even, i.e. if statement has not been executed for any iteration. Therefore for the array [1, 9, 8] the if is executed in third iteration of the loop and hence the else present after the for loop is ignored. In case of array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed.


    Read full article from Using else conditional statement with for loop in python - GeeksforGeeks


    Spring Boot interceptor example



    Spring Boot interceptor example

    In this page I will show you how to use interceptor in Spring Boot. You can use interceptor handling common business logic. The structure of project is like following.


    Read full article from Spring Boot interceptor example


    java - Spring AOP. Getting the bean name from the JoinPoint - Stack Overflow



    java - Spring AOP. Getting the bean name from the JoinPoint - Stack Overflow

    Stream.of(joinPoint.getTarget().getClass().getAnnotationsByType(Service.class))        .forEach(q -> logger.info(q.value()));

    to get the bean as declared by @Service annotation.

    However, not all beans are created this way. Some are created by @Bean annotated methods, some can even be added manually to the the context. So, if you annotate your bean classes with @Component, @Service, @Qualifier etc. and use @ComponentScan you might get what you want. You just need to remember that it's not the universal way to retrieve all beans currently available in the context (it will not work for classes without any annotations/metadata).


    Read full article from java - Spring AOP. Getting the bean name from the JoinPoint - Stack Overflow


    spring - What does $$ and means in java stacktrace? - Stack Overflow



    spring - What does $$ and means in java stacktrace? - Stack Overflow

    $ is an allowed character in class names.

    The name SimpleDetectorPersistenceService$$EnhancerBySpringCGLIB$$66303639 hints that it is a class which was dynamically generated at runtime by Spring framework using CGLIB.

    They use $$ and a numeric offset to make this class name unique to avoid conflicts with existing classes.

    The string (<generated>) in the stracktrace too was generated by CGLIB:
    When CGLIB creates a class at runtime it uses <generated> as placeholder for the name of the source file. The stacktrace then simply prints this string instead of the real source file and line number.


    Read full article from spring - What does $$ and means in java stacktrace? - Stack Overflow


    My daily Java: cglib: The missing manual



    My daily Java: cglib: The missing manual

    The byte code instrumentation library cglib is a popular choice among many well-known Java frameworks such as Hibernate (not anymore) or Spring for doing their dirty work. Byte code instrumentation allows to manipulate or to create classes after the compilation phase of a Java application. Since Java classes are linked dynamically at run time, it is possible to add new classes to an already running Java program. Hibernate uses cglib for example for its generation of dynamic proxies. Instead of returning the full object that you stored ina a database, Hibernate will return you an instrumented version of your stored class that lazily loads some values from the database only when they are requested. Spring used cglib for example when adding security constraints to your method calls. Instead of calling your method directly, Spring security will first check if a specified security check passes and only delegate to your actual method after this verification. Another popular use of cglib is within mocking frameworks such as mockito, where mocks are nothing more than instrumented class where the methods were replaced with empty implementations (plus some tracking logic).

    Read full article from My daily Java: cglib: The missing manual


    NoSQL Data Modeling Techniques – Highly Scalable Blog



    NoSQL Data Modeling Techniques – Highly Scalable Blog

    NoSQL databases are often compared by various non-functional criteria, such as scalability, performance, and consistency. This aspect of NoSQL is well-studied both in practice and theory because specific non-functional properties are often the main justification for NoSQL usage and fundamental results on distributed systems like the CAP theorem apply well to NoSQL systems.  At the same time, NoSQL data modeling is not so well studied and lacks the systematic theory found in relational databases. In this article I provide a short comparison of NoSQL system families from the data modeling point of view and digest several common modeling techniques.


    Read full article from NoSQL Data Modeling Techniques – Highly Scalable Blog


    Jackson: Ignore null and empty fields - Wilddiary.com



    Jackson: Ignore null and empty fields - Wilddiary.com

    The Jackson Object Mapper can take serialization option that controls the serialization process. You can set the option by calling setSerializationInclusion() and pass in the desired JsonInclude serialization option.


    Read full article from Jackson: Ignore null and empty fields - Wilddiary.com


    ProcessBuilder in Java to create a basic online Judge - GeeksforGeeks



    ProcessBuilder in Java to create a basic online Judge - GeeksforGeeks

    We have discussed Process and Runtime to create an external process. In this post, ProcessBuilder is discussed which serves the same purpose.

    Let us understand an application where we need to get source code and find out the language. The application needs a string (containing source code) as input. The application needs to find out the language in which source code in written. Source codes will be having a relevant extension. For example –

    • Code in C language will have ".c" extension
    • Code in C++ will have ".cpp" extension
    • Code in Java will have ".java" extension
    • Code in Python will have ".py" extension

    Using the name of input file the required language, to be used, can be found out.

    Recall that compiling a code in java is done with command –
    "javac Main.java"
    and to execute it we use –
    "java Main"

    Similar commands are there for other languages. Therefore we need a separate text file containing all the commands which our software should execute one by one.

    In case of error (Runtime or Compiler Errors) our application should write the error logs in a separate text file. Whatever output the source code is producing, our application should write it in another text file.

    We use "ProcessBuilder" class in "Language" package which can execute OS processes.


    Read full article from ProcessBuilder in Java to create a basic online Judge - GeeksforGeeks


    Optimization Tips for Python Code - GeeksforGeeks



    Optimization Tips for Python Code - GeeksforGeeks

    In this article, some interesting optimization tips for Faster Python Code are discussed. These techniques help to produce result faster in a python code.

    1. Use builtin functions and libraries: Builtin functions like map() are implemented in C code. So the interpreter doesn't have to execute the loop, this gives a considerable speedup.
      The map() function applies a function to every member of iterable and returns the result. If there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables.


    Read full article from Optimization Tips for Python Code - GeeksforGeeks


    Prufer Code to Tree Creation - GeeksforGeeks



    Prufer Code to Tree Creation - GeeksforGeeks

    What is Prufer Code?
    Given a tree (represented as graph, not as a rooted tree) with n labeled nodes with labels from 1 to n, a Prufer code uniquely idetifies the tree. The sequence has n-2 values.

    How to get Prufer Code of a tree?

    1. Initialize Prufer code as empty.
    2. Start with a leaf of lowest label say x. Find the vertex connecting it to the rest of tree say y. Remove x from the tree and add y to the Prufer Code
    3. Repeat above step 2 until we are left with two nodes.

    Read full article from Prufer Code to Tree Creation - GeeksforGeeks


    cql - How to change PARTITION KEY column in Cassandra? - Stack Overflow



    cql - How to change PARTITION KEY column in Cassandra? - Stack Overflow

    You simply cannot alter the primary key of a Cassandra table. You need to create another table with your new schema and perform a data migration. I would suggest that you use Spark for that since it is really easy to do a migration between two tables with only a few lines of code.


    Read full article from cql - How to change PARTITION KEY column in Cassandra? - Stack Overflow


    Number of even substrings in a string of digits - GeeksforGeeks



    Number of even substrings in a string of digits - GeeksforGeeks

    Given a string of digits 0 – 9. The task is to count number of substrings which when convert into integer form an even number.


    Read full article from Number of even substrings in a string of digits - GeeksforGeeks


    How ranking in Google Search Works ! - GeeksforGeeks



    How ranking in Google Search Works ! - GeeksforGeeks

    Search Engine: A program that searches for and identifies items in a database that corresponds to keywords or characters specified by the user, used especially for finding particular sites on the World Wide Web.
    Example: Google search engine, Yahoo , Bing etc.

    Search Engine Index: A search engine index is a database that correlates keyword and websites so that the search engine can display websites that match the user's search query.
    For example, if the user searches for Cheetah running speed, then the software spider searches these terms in the search engine index.

    Web crawler: The first thing you need to understand is what a Web Crawler or Spider is and how it works. A Search Engine Spider (also known as a crawler, Robot, SearchBot or simply a Bot) is a program that most search engines use to find what's new on the Internet. Google's web crawler is known as GoogleBot. The program starts at a website and follows every hyperlink on each page.
    So it can be said that everything on the web will eventually be found and spidered, as the so called "spider" crawls from one website to another. When a web crawler visits one of your pages, it loads the site's content into a database. Once a page has been fetched, the text of your page is loaded into the search engine's index, which is a massive database of words, and where they occur on different web pages.

    Robots.txt file: Web crawlers crawls on few websites without approval. Therefore every website includes a robots.txt file which contains instructions for the spider(web crawler) on which parts of the website to index, and which parts to ignore.


    Read full article from How ranking in Google Search Works ! - GeeksforGeeks


    兄弟单词 — 两种算法实现 | 勇幸|Thinking



    兄弟单词 — 两种算法实现 | 勇幸|Thinking

    兄弟单词这个题目最初见于《编程珠玑》,但是里面给出的方法是最笨的,一般不提倡采用吧;这个题目在之前的百度面试中也遇到过,本文实现两种方法的代码,方法如下:

    方案一:使用数据结构 map<key,list>。兄弟单词共用一个签名key,key为单词内部排序后的词条,list存储同一key的单词集合;相对于编程珠玑中的方法,该方法在空间上节省了每个单词一个key的空间;在时间上,不再需要二分查找,O(1)的查找;但是这种方法还可以优化,见方案二

    方案二:使用trie树。trie树又称字典树,在面试题中关于"字符串"与"数字串"类型的问题中高频出现,非常实用。对于兄弟单词,兄弟单词公用一个key自不必说,只是trie的节点结构应该多出一个域list,用来存储key对应的兄弟单词;具体节点结构应该为


    Read full article from 兄弟单词 — 两种算法实现 | 勇幸|Thinking


    Twitter online 两题 | 勇幸|Thinking



    Twitter online 两题 | 勇幸|Thinking

    今天有个群里发了两道twitter online的题目,看了下,练手写一下。

    题一:

    A zero-indexed array A consisting of N different integers is given. The array contains all integers in the range [0..N−1]. Sets S[K] for 0 ≤ K < N are defined as follows: S[K] = { A[K], A[A[K]], A[A[A[K]]], ... }. Sets S[K] are finite for each K.

    Write a function:

    class Solution { public int solution(int[] A); }

    that, given an array A consisting of N integers, returns the size of the largest set S[K] for this array. The function should return 0 if the array is empty.

    原题不存在数组元素不小于len的情况,后面的两种解法都是考虑元素有大于len的情况,开始没看清,做了个稍微复杂的情况;区别在于,如果元素不越界,S集合就是一个个的环,当元素值等于下标值,环大小为1;如果元素有越界情况,则S集合就不一定是环,就需要记录之前遍历的集合大小了,先给出本题的解法,后面讨论元素越界的情况。


    Read full article from Twitter online 两题 | 勇幸|Thinking


    Google 面试题 | 检查子序列



    Google 面试题 | 检查子序列

    这道题就是简单的两个指针问题考察,能够快速想到双指针并且能够正确估算出时间复杂度,那么此题就可以得到 hire 的评价。


    Read full article from Google 面试题 | 检查子序列


    Notes for Harvard CS75 Web Development Lecture 9 Scalability by David Malan | Nine notes



    Notes for Harvard CS75 Web Development Lecture 9 Scalability by David Malan | Nine notes

    • Is IP address blocked in some countries/regions?
    • SFTP vs. FTP. SFTP is secure and all the traffic is encrypted, which is important for user names and passwords
    • Some hosting companies may offer you some unbelievable features, like unlimited storage spac, at a very low price. It's very likely that you and another hundreds users are sharing the same machine and contending for resources. This is because sometime people actually don't need that many resources.
    • Virtual private server. May still share one machine with other users, but you have your own copy of the operating system. Run multiple virtual machine on a physical machine. Only you and the system administrators have access to your files
    • If you want more privacy, then probably you have to operate your own servers


    Read full article from Notes for Harvard CS75 Web Development Lecture 9 Scalability by David Malan | Nine notes


    Getting Out Ahead Of This One: Uber Has Apologize... | ClickHole



    Getting Out Ahead Of This One: Uber Has Apologize... | ClickHole

    Getting Out Ahead Of This One: Uber Has Apologized In Advance If Anyone Finds Out About Something Called 'Project Judas' From price gouging to workplace discrimination and driver mistreatment, Uber has been no stranger to controversy in recent years, but it appears an even more damning scandal may now be brewing. Earlier today, the company publicly apologized in advance in case anyone ends up finding out about something called "Project Judas." Well, looks like they're really trying to nip this one in the bud. "Should the as-yet-undisclosed details of Project Judas someday come to light, we would like to take this moment to offer a full apology," read a statement issued by the company this morning. "If our emails are ever hacked, causing the location of the testing facilities to become known, then we express our sincerest regrets for that. We are currently unable to stop Project Judas even if we wanted to.

    Read full article from Getting Out Ahead Of This One: Uber Has Apologize... | ClickHole


    Testing Asynchronous Code | Wix Engineering



    Testing Asynchronous Code | Wix Engineering

    Asynchronous code is hard. Everyone knows that. Writing asynchronous tests is even harder. Recently I fixed a flaky test and I want to share some thoughts about writing asynchronous tests.

    In this post we explore a common problem with asynchronous tests—how to force a test to take a specific ordering between threads, and forcing some operations by some threads to complete before other operations by other threads. Normally we do not want to enforce ordering between the execution of different threads because it defeats the reason to use threads, which is to allow concurrency and to allow the CPU to select the best order of execution given the current resources and state of the application. But in the case of testing, deterministic ordering is sometimes required to ensure the test stability.


    Read full article from Testing Asynchronous Code | Wix Engineering


    Develop Spring Redis applications



    Develop Spring Redis applications

    The open source Spring framework is a mainstay of enterprise application development, with millions of Java developers in its user ranks. Spring Data is an umbrella open source project that makes it easier to build Spring-powered applications that use data access technologies — including modern ones such as nonrelational databases, MapReduce frameworks, and cloud-based data services. One such technology is Redis (REmote DIctionary Server) — an open source, advanced, NoSQL key-value datastore that is written in ANSI C. In this article I introduce you to Redis, its data model and data types, and its advantages. Then, you'll see how to use Spring Data Redis to build a sample application.


    Read full article from Develop Spring Redis applications


    Vi and Vim Macro Tutorial: How To Record and Play



    Vi and Vim Macro Tutorial: How To Record and Play

    High Level Steps to Record and Play inside Vim

    1. Start recording by pressing q, followed by a lower case character to name the macro
    2. Perform any typical editing, actions inside Vim editor, which will be recorded
    3. Stop recording by pressing q
    4. Play the recorded macro by pressing @ followed by the macro name
    5. To repeat macros multiple times, press : NN @ macro name. NN is a number


    Read full article from Vi and Vim Macro Tutorial: How To Record and Play


    vi tips and tricks: Ten cool commands sure to impress your friends



    vi tips and tricks: Ten cool commands sure to impress your friends

    When coming to grips with the vi editor—either for the first time or as a regular user—most people tend to have a grasp of the core command set that allows them to perform those functions they use most regularly: navigating or saving a file; inserting, updating, deleting, or searching for data; or quitting without saving changes.

    However, the vi editor is extremely powerful and rich in features and functionality. Even after many years of use, you can still uncover new commands that you didn't realize existed. The commands covered in this article are amongst those less well known, but they can help you to work smarter by short-cutting existing methods you may use or allowing you to do something that you never realized you could do with vi.

    Before we start just a recap on the two modes of vi: command and insert. Command mode allows the user to execute commands to modify text, navigate around the file or control your vi session in some way. Insert mode puts anything you type into the current file in your vi session. When you start vi you start in command mode. Once in insert mode you can switch back to command mode by hitting the Escape key. Hitting the Escape key whilst in command mode leaves you in command mode. All of the commands covered in this article should be executed from command mode.


    Read full article from vi tips and tricks: Ten cool commands sure to impress your friends


    java - Jedis waitForLock Time Limit or Override - Stack Overflow



    java - Jedis waitForLock Time Limit or Override - Stack Overflow

    In my investigation of an issue I am having with Jedis getting resources from Redis, I discovered that Spring Data Redis has a method called waitForLock that goes into interation of Thread.sleep when there is a cache lock key name in Redis. This iteration goes on till the cache lock key is out of Redis so it may be a very long time (like 27 minutes in my case).

    Is there a config that exists for me to override this behaviour, that is, creating a limit for which Spring Data Redis will check this lock key before throwing exception.

    Or is there another way around it other than config settings.


    Read full article from java - Jedis waitForLock Time Limit or Override - Stack Overflow


    Java Core Debugging using IBM Thread and Monitor Dump Analyzer for Java (ECM Community Blog)



    Java Core Debugging using IBM Thread and Monitor Dump Analyzer for Java (ECM Community Blog)

    Abstract: Problems which cause Java processes to dump threads to a core file can be solved with the help of an IBM DeveloperWorks tool created by Jinwoo Hwang.

     

    Introduction

    Some error conditions in an IBM® Java Virtual Machine (JVM) running under IBM WebSphere® Application Server result in a crash. The output of a crash is a Java core file. The Watson Explorer Content Analytics runtime is instrumented to output all running Java threads, at the time of a system-critical error. These core files are written to the Content Analytics/logs directory and are included in the output of the command.


    Read full article from Java Core Debugging using IBM Thread and Monitor Dump Analyzer for Java (ECM Community Blog)


    How to Analyze Java Thread Dumps - DZone Performance



    How to Analyze Java Thread Dumps - DZone Performance

    We will introduce the three most commonly used methods. Note that there are many other ways to get a thread dump. A thread dump can only show the thread status at the time of measurement, so in order to see the change in thread status, it is recommended to extract them from 5 to 10 times with 5-second intervals.


    Read full article from How to Analyze Java Thread Dumps - DZone Performance


    Labels

    Algorithm (219) Lucene (130) LeetCode (97) Database (36) Data Structure (33) text mining (28) Solr (27) java (27) Mathematical Algorithm (26) Difficult Algorithm (25) Logic Thinking (23) Puzzles (23) Bit Algorithms (22) Math (21) List (20) Dynamic Programming (19) Linux (19) Tree (18) Machine Learning (15) EPI (11) Queue (11) Smart Algorithm (11) Operating System (9) Java Basic (8) Recursive Algorithm (8) Stack (8) Eclipse (7) Scala (7) Tika (7) J2EE (6) Monitoring (6) Trie (6) Concurrency (5) Geometry Algorithm (5) Greedy Algorithm (5) Mahout (5) MySQL (5) xpost (5) C (4) Interview (4) Vi (4) regular expression (4) to-do (4) C++ (3) Chrome (3) Divide and Conquer (3) Graph Algorithm (3) Permutation (3) Powershell (3) Random (3) Segment Tree (3) UIMA (3) Union-Find (3) Video (3) Virtualization (3) Windows (3) XML (3) Advanced Data Structure (2) Android (2) Bash (2) Classic Algorithm (2) Debugging (2) Design Pattern (2) Google (2) Hadoop (2) Java Collections (2) Markov Chains (2) Probabilities (2) Shell (2) Site (2) Web Development (2) Workplace (2) angularjs (2) .Net (1) Amazon Interview (1) Android Studio (1) Array (1) Boilerpipe (1) Book Notes (1) ChromeOS (1) Chromebook (1) Codility (1) Desgin (1) Design (1) Divide and Conqure (1) GAE (1) Google Interview (1) Great Stuff (1) Hash (1) High Tech Companies (1) Improving (1) LifeTips (1) Maven (1) Network (1) Performance (1) Programming (1) Resources (1) Sampling (1) Sed (1) Smart Thinking (1) Sort (1) Spark (1) Stanford NLP (1) System Design (1) Trove (1) VIP (1) tools (1)

    Popular Posts